Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding of negative numbers in Javascript

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 ?

like image 247
Po1nt Avatar asked Jan 11 '17 09:01

Po1nt


People also ask

How do you round a number 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).

How do I round to 2 decimal places in JavaScript?

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.

Can you use negative numbers in JavaScript?

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.


2 Answers

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))
  )
});
like image 161
Pranav C Balan Avatar answered Sep 30 '22 19:09

Pranav C Balan


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
like image 36
Nina Scholz Avatar answered Sep 30 '22 21:09

Nina Scholz