Rounding Negative Numbers in Javascript

We encountered a problem with Math.round () in JavaScript. The problem is that this function does not round correctly for negative numbers. For instance:

1.5 ~ = 2

0.5 ~ = 1

-0.5 ~ = 0 // Invalid

-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 - -2.

Is there any standard way to properly round negative numbers in Javascript?

+7
source share
4 answers

You can save the character and apply it 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
Run codeHide result
+5
source

Math.round , , . Math.sign Math.abs, .

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))
  )
});
Hide result
+14

Math.ceil(num) num, - 1, num ,

if (num < 0) {
  num = Math.ceil(num) - 1;
} else {
  num = Math.ceil(num);
}
+1
var r = (Math.random() * 200) - 100;

? , , "":

var n = r + (r < 0 ? -0.5 : 0.5) | 0;

| 0 | 0 - js, "" ( ) , .

, ( Math.floor), , , Math.floor(-3.2) -4.


You can even do something similar to @ Balan's answer (I like this one and the one below, but I feel that it is, otherwise the ternary operator will be faster to the touch - although I'm probably mistaken because the libraries Mathwere very quickly)

var n = (r + Math.sign(r) / 2) | 0;

probably the fastest, most elegant way:

var n = Math.floor(r + 0.5);

example:

var body = document.getElementById("myTable").children[1];
var i, iMax = 100, r, tr, td;
for (i = 0; i < iMax; i++) {
    r = Math.random() * 200 - 100;
    tr = document.createElement("tr");
    td = document.createElement("td");
    td.innerHTML = r;
    tr.appendChild(td);
    td = document.createElement("td");
    td.innerHTML = (r + Math.sign(r) / 2) | 0;
    tr.appendChild(td);
    body.appendChild(tr);
}
#myTable {
    min-width: 250px;
}
<table id="myTable">
 <thead>
  <tr>
   <th>float</th>
   <th>round</th>
  </tr>
 </thead>
 <tbody>
 </tbody>
</table>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1666474/


All Articles