Simplest way of getting the number of decimals in a number in JavaScript(在 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.
例如
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).
如果你不想将 this 绑定到原型,你可以使用 this:
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;
}
布莱克
EDIT by Black:
我已经修复了该方法,使其也适用于较小的数字,例如 0.000000001
I have fixed the method, to also make it work with smaller numbers like 0.000000001
Number.prototype.countDecimals = function () {
if (Math.floor(this.valueOf()) === this.valueOf()) return 0;
var str = this.toString();
if (str.indexOf(".") !== -1 && str.indexOf("-") !== -1) {
return str.split("-")[1] || 0;
} else if (str.indexOf(".") !== -1) {
return str.split(".")[1].length || 0;
}
return str.split("-")[1] || 0;
}
var x = 23.453453453;
console.log(x.countDecimals()); // 9
var x = 0.0000000001;
console.log(x.countDecimals()); // 10
var x = 0.000000000000270;
console.log(x.countDecimals()); // 13
var x = 101; // Integer number
console.log(x.countDecimals()); // 0
这篇关于在 JavaScript 中获取数字中小数位数的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 JavaScript 中获取数字中小数位数的最简单方法


基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01