数量的规模和精度

Cod*_*kie 5 javascript jquery

我想从以下示例中的数字中获得比例和精度.

var x = 1234.567;

我没有看到内置任何功能.scale.precision功能,我不确定最好的方法是什么.

the*_*dox 6

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.


Vis*_*ioN 5

另一种先进的解决方案(如果我正确理解你的尺度精度是什么意思):

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.

  • 我个人认为这个解决方案非常棒,正是我所需要的,尽管所有的评论...... (2认同)

小智 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)