I'm looking to get the scale and precision from a number in the following example.
var x = 1234.567;
I'm not seeing any .scale
or .precision
functions built in and I'm not sure what the best way to right one is.
I'm looking to get the scale and precision from a number in the following example.
var x = 1234.567;
I'm not seeing any .scale
or .precision
functions built in and I'm not sure what the best way to right one is.
3 Answers
Reset to default 7You can use Number.prototype.toFixed()
var x = 1234.56780123;
x.toFixed(2); // output: 1234.57
x.toFixed(3); // output: 1234.568
x.toFixed(4); // output: 1234.5680
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() method that gives to a number with specified length.
For example:
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
and so on.
According to comment
Is there a way to check that the string contain .
?
var x = 1234.567
x.toString().indexOf('.'); // output: 4
Note
.indexof()
return first index of target else -1
.
Another advanced solution (if I correctly understand what you mean by scale and precision):
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 number is not float function returns null
.
0.1 + 0.1 + 0.1
. You'd expect that to be0.3
. Well it's not. It's0.30000000000000004
. Suddenly, your precision has shot up. – Eric Commented Jun 8, 2012 at 17:36