数字量表和精度 [英] Scale and Precision from Number
本文介绍了数字量表和精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的示例中,我希望从数字中获得比例和精度.
I'm looking to get the scale and precision from a number in the following example.
var x = 1234.567;
我没有看到任何内置的.scale
或.precision
函数,并且不确定哪种正确的最佳方法是什么.
I'm not seeing any .scale
or .precision
functions built in and I'm not sure what the best way to right one is.
推荐答案
var x = 1234.567;
var parts = x.toString().split('.');
parts[0].length; // output: 4 for 1234
parts[1].length; // output: 3 for 567
注意
JavaScript具有 toPrecision() 方法可得出具有指定长度的数字.
NOTE
Javascript has toPrecision() method that gives to a number with specified length.
例如:
var x = 1234.567;
x.toPrecision(4); // output: 1234
x.toPrecision(5); // output: 1234.5
x.toPrecision(7); // output: 1234.56
但是
x.toPrecision(5); // output: 1235
x.toPrecision(3); // output: 1.23e+3
以此类推.
有没有办法检查字符串是否包含.
?
Is there a way to check that the string contain .
?
var x = 1234.567
x.toString().indexOf('.'); // output: 4
注意
.indexof()
返回目标的第一个索引,否则为-1
.
Note
.indexof()
return first index of target else -1
.
这篇关于数字量表和精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文