Scale and accuracy from the room

I want to get scale and accuracy from a number in the following example.

var x = 1234.567;

I don't see any built-in functions .scaleor .precision, and I'm not sure what the best way to do the right one.

+5
source share
3 answers
var x = 1234.567;

var parts = x.toString().split('.');

parts[0].length; // output: 4 for 1234

parts[1].length; // output: 3 for 567

Note

Javascript has toPrecision () , which gives a number with the specified length.

For instance:

var x = 1234.567;

x.toPrecision(4); // output: 1234

x.toPrecision(5); // output: 1234.5

x.toPrecision(7); // output: 1234.56

But

x.toPrecision(5); // output: 1235

x.toPrecision(3); // output: 1.23e+3 

etc.

According to the comment

Is there a way to check what the string contains .?

var x = 1234.567

x.toString().indexOf('.'); // output: 4

Note

.indexof()return the first index of the else target -1.

+6
source

Another advanced solution (if I understand correctly what you mean by scale and accuracy):

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

If the number does not return a float function null.

+5

:

var x = 1234.56780123;

x.toFixed(2); // output: 1234.56
x.toFixed(3); // output: 1234.568
x.toFixed(4); // output: 1234.5680
+2

All Articles