在JavaScript中获取数字中的小数位数的最简单方法 [英] Simplest way of getting the number of decimals in a number in JavaScript
问题描述
有没有更好的方法来计算数字上的小数位数而不是我的例子?
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;
更好的意思是我更快地执行和/或使用本机JavaScript函数,即。类似于nbr.getDecimals()。
By better I mean faster to execute and/or using a native JavaScript function, ie. something like nbr.getDecimals().
提前致谢!
编辑:
修改series0ne答案后,我能管理的最快方式是:
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);
速度测试: http://jsperf.com/checkdecimals
推荐答案
Number.prototype.countDecimals = function () {
if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
return this.toString().split(".")[1].length || 0;
}
当绑定到原型时,这允许您获取小数( countDecimals();
)直接来自数字变量。
When bound to the prototype, this allows you to get the decimal count (countDecimals();
) directly from a number variable.
EG
var x = 23.453453453;
x.countDecimals(); // 9
它的工作原理是将数字转换为字符串,在处分割。并返回数组的最后一部分,如果数组的最后一部分未定义则返回0(如果没有小数点则会出现)。
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;
}
这篇关于在JavaScript中获取数字中的小数位数的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!