简体   繁体   English

检查小数部分后的位数

[英]Check the number of digits after the decimal part

I need to validate a number accordingly to its number of digits after the decimal part.我需要根据小数部分后的位数验证一个数字。

I am using with success the following code but, I would like to know:我正在成功使用以下代码,但我想知道:

  • Is there another better way to achieve the same result?有没有另一种更好的方法来达到同样的结果? Maybe using some native Math functional.也许使用一些原生数学函数。

Notes: I am aware of regular expression, but I am looking for a math approach.注意:我知道正则表达式,但我正在寻找一种数学方法。

 var max = 2; // max number of digits after decimal places var value = 10.154; var s = value.toString().split('.') if (s[1].length > max) { alert('invalid'); } else { alert('ok'); }

I believe this is the best way of doing it as there is no built in Javascript function that will achieve what you want.我相信这是最好的方法,因为没有内置的 Javascript 函数可以实现你想要的。 This solution will work everywhere except in continental Europe where they use a comma(,) delimiter for decimals instead of a period(.)除了在欧洲大陆使用逗号(,)分隔符而不是句点(。)

You could also do this, but it wont work for negative numbers你也可以这样做,但它不适用于负数

var value = 10.154;
value = Math.abs(value);
var decimal = value - Math.floor(value)
var length = decimal.toString().length;

You may use Python's round() function:你可以使用 Python 的round()函数:

>>> num = 10.542
>>> round(num, 2) == num
False
>>> num = 12.32
>>> round(num, 2) == num
True

Or或者

>>> num = 12.32
>>> round(num, 2) >= num
True
>>> num = 12.3
>>> round(num, 2) >= num
True
>>> num = 12.324
>>> round(num, 2) >= num
False

You can do this:你可以这样做:

var value = 10.154;
var length = value.toString().length - (value.toString().indexOf('.') + 1)

When determining number of digits, one needs to deal with a number as a string. 在确定数字位数时,需要将数字作为字符串来处理。 So you'll need to do something similar to what you're doing. 因此,您需要执行与您正在执行的操作类似的操作。 Or just use .toFixed() to get rid of extra digits. 或者只是使用.toFixed()摆脱多余的数字。

In the computer, the number has a whole floating point decimal.在计算机中,数字有一个完整的浮点小数。 So 10.154 is in fact 10.15400000000 (to whatever level of accuracy the language goes).所以 10.154 实际上是 10.15400000000(无论语言的准确度如何)。

So if you want to check if it has > max decimal values then you go: you'll multiply the whole value with 10^x and then modulus 1 it.因此,如果您想检查它是否具有 > 最大十进制值,那么您可以:将整个值与 10^x 相乘,然后对它进行模数 1。 If it's not 0 then you have more deceimal values than the max that you set.如果它不是 0,那么您的十进制值比您设置的最大值多。

So per your example 10.154 (3 decimal points) * 10^2 (your max) = 1015.4 1015.4 % 1 = 0.4 so "invalid"因此,根据您的示例 10.154(3 个小数点)* 10^2(您的最大值)= 1015.4 1015.4 % 1 = 0.4 所以“无效”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM