简体   繁体   中英

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. 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:

>>> 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.

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).

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. If it's not 0 then you have more deceimal values than the max that you set.

So per your example 10.154 (3 decimal points) * 10^2 (your max) = 1015.4 1015.4 % 1 = 0.4 so "invalid"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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