Rounding of negative numbers in Javascript
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
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 try using Math.ceil(num) to round num and then - 1 if num was negative, e.g.
if (num < 0) {
num = Math.ceil(num) - 1;
} else {
num = Math.ceil(num);
}