问题
This question already has an answer here:
- Is there a reliable way in JavaScript to obtain the number of decimal places of an arbitrary number? 7 answers
Is there a better way of figuring out the number of decimals on a number than in my example?
var nbr = 37.435.45;
var decimals = (nbr!=Math.floor(nbr))?(nbr.toString()).split('.')[1].length:0;
By better I mean faster to execute and/or using a native JavaScript function, ie. something like nbr.getDecimals().
Thanks in advance!
EDIT:
After modifying series0ne answer, the fastest way I could manage is:
var val = 37.435345;
var countDecimals = function(value) {
if (Math.floor(value) !== value)
return value.toString().split(".")[1].length || 0;
return 0;
}
countDecimals(val);
Speed test: http://jsperf.com/checkdecimals
回答1:
Number.prototype.countDecimals = function () {
if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
return this.toString().split(".")[1].length || 0;
}
When bound to the prototype, this allows you to get the decimal count (countDecimals();) directly from a number variable.
E.G.
var x = 23.453453453;
x.countDecimals(); // 9
It works by converting the number to a string, splitting at the . and returning the last part of the array, or 0 if the last part of the array is undefined (which will occur if there was no decimal point).
If you do not want to bind this to the prototype, you can just use this:
var countDecimals = function (value) {
if(Math.floor(value) === value) return 0;
return value.toString().split(".")[1].length || 0;
}
回答2:
Adding to series0ne answer if you want to have the code not throw an error for an integer number and get a result of 0 when there are no decimals use this:
var countDecimals = function (value) {
if ((value % 1) != 0)
return value.toString().split(".")[1].length;
return 0;
};
回答3:
Regex are very very not efficient in calculations, they are mean if you can go another way. So I would avoid them :)
Things like "Number % 1" return the rounded decimal value (2.3 % 1 = 0.2999999999999998), and in a general way I would advice you to use strings as early as possible, since approximations with real numbers can change the number of decimals.
So yours is fine, but I'll look a way to optimize it.
Edit:
function CountDecimalDigits(number)
{
var char_array = number.toString().split(""); // split every single char
var not_decimal = char_array.lastIndexOf(".");
return (not_decimal<0)?0:char_array.length - not_decimal;
}
来源:https://stackoverflow.com/questions/17369098/simplest-way-of-getting-the-number-of-decimals-in-a-number-in-javascript