var x = 1234.567;
var parts = x.toString().split('.');
parts[0].length; // output: 4 for 1234
parts[1].length; // output: 3 for 567
Run Code Online (Sandbox Code Playgroud)
Javascript具有toPrecision()方法,该方法赋予具有指定长度的数字.
例如:
var x = 1234.567;
x.toPrecision(4); // output: 1234
x.toPrecision(5); // output: 1234.5
x.toPrecision(7); // output: 1234.56
Run Code Online (Sandbox Code Playgroud)
但
x.toPrecision(5); // output: 1235
x.toPrecision(3); // output: 1.23e+3
Run Code Online (Sandbox Code Playgroud)
等等.
有没有办法检查字符串是否包含.?
var x = 1234.567
x.toString().indexOf('.'); // output: 4
Run Code Online (Sandbox Code Playgroud)
.indexof()返回目标的第一个索引-1.
另一种先进的解决方案(如果我正确理解你的尺度和精度是什么意思):
function getScaleAndPrecision(x) {
x = parseFloat(x) + "";
var scale = x.indexOf(".");
if (scale == -1) return null;
return {
scale : scale,
precision : x.length - scale - 1
};
}
var res = getScaleAndPrecision(1234.567);
res.scale; // for scale
res.precision; // for precision
Run Code Online (Sandbox Code Playgroud)
如果number不是float函数返回null.
小智 5
您可以使用:
var x = 1234.56780123;
x.toFixed(2); // output: 1234.56
x.toFixed(3); // output: 1234.568
x.toFixed(4); // output: 1234.5680
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9125 次 |
| 最近记录: |