Reputation: 111
Without jQuery, how can I round a float number to 2 non-zero decimals (but only when needed - 1.5 instead of 1.50)?
Just like this:
2.50000000004 -> 2.5
2.652 -> 2.65
2.655 -> 2.66
0.00000204 -> 0.000002
0.00000205 -> 0.0000021
I tried this code:
var r = n.toFixed(1-Math.floor(Math.log10(n)));
but n=0.00000205
implies r=0.0000020
, which is in conflict with conditions above.
But n=0.0000020501
implies r=0.0000021
, which is OK, so the error is only for 5 as a last decimal, which should be rounded up.
Upvotes: 2
Views: 2196
Reputation: 21
Thank's for the @Arnauld answer. Just added decimals
parameter.
function roundToDecimals(n, decimals) {
var log10 = n ? Math.floor(Math.log10(n)) : 0,
div = log10 < 0 ? Math.pow(10, decimals - log10 - 1) : Math.pow(10, decimals);
return Math.round(n * div) / div;
}
var numDecimals = 2
var test = [
2.50000000004,
2.652,
2.655,
0.00000204,
0.00000205,
0.00000605
];
test.forEach(function(n) {
console.log(n, '->', roundToDecimals(n, numDecimals));
});
Upvotes: 0
Reputation: 6110
This should do what you want:
function twoDecimals(n) {
var log10 = n ? Math.floor(Math.log10(n)) : 0,
div = log10 < 0 ? Math.pow(10, 1 - log10) : 100;
return Math.round(n * div) / div;
}
var test = [
2.50000000004,
2.652,
2.655,
0.00000204,
0.00000205,
0.00000605
];
test.forEach(function(n) {
console.log(n, '->', twoDecimals(n));
});
Upvotes: 8