We have come across a problem with Math.round() in JavaScript. The problem is that this function doesn't round correctly for negative numbers. For example :
1.5 ~= 2
0.5 ~= 1
-0.5 ~= 0 // Wrong
-1.5 ~= -1 // Wrong
And this is not correct according to arithmetic rounding. The correct numbers for -0.5 should be -1 and -1.5 should be -2.
Is there any standard way, to correctly round negative numbers in Javascript ?
The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).
Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.
To use negative numbers, just place a minus (-) character before the number we want to turn into a negative value: let temperature = -42; What we've seen in this section makes up the bulk of how we will actually use numbers.
Apply Math.round
after converting to a positive number and finally roll back the sign. Where you can use Math.sign
method to get the sign from the number and Math.abs
to get the absolute of the number.
console.log(
Math.sign(num) * Math.round(Math.sign(num) * num),
// or
Math.sign(num) * Math.round(Math.abs(num))
)
var nums = [-0.5, 1.5, 3, 3.6, -4.8, -1.3];
nums.forEach(function(num) {
console.log(
Math.sign(num) * Math.round(Math.sign(num) * num),
Math.sign(num) * Math.round(Math.abs(num))
)
});
You could save the sign and apply later, in ES5;
function round(v) {
return (v >= 0 || -1) * Math.round(Math.abs(v));
}
console.log(round(1.5)); // 2
console.log(round(0.5)); // 1
console.log(round(-1.5)); // -2
console.log(round(-0.5)); // -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With