Reputation: 59
Is there any function in JavaScript that will return the unit size of the least significant digit of a decimal number?
For example:
if the number is 1.5, return 0.1
if the number is 0.15, return 0.01
if the number is 0.10, return 0.01 (yeah, that's right)
if the number is 0.100, return 0.001
And for an integer value, just return 1.
For example:
if the number is 15, return 1
if the number is 150, return 1
if the number is -32, return 1
Upvotes: 2
Views: 209
Reputation: 12239
Find the position of the period and compare it to the length of the string:
function smallestDecimalUnit(s) {
var pos = s.indexOf('.');
if (pos == -1) {
return 1;
}
return Math.pow(10, pos - s.length + 1);
}
function test(s) {
document.write(s + ' → ' + smallestDecimalUnit(s) + '<br><br>');
}
test('1.5');
test('0.15');
test('0.10');
test('15');
test('150');
body {
font-family: sans-serif;
}
Upvotes: 4