Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript roundoff number to nearest 0.5

Tags:

javascript

People also ask

Can 0.5 Be round off?

0.5 rounded off to the nearest whole number is 1. Since, the value after decimal is equal to 5, then the number is rounded up to the next whole number. Hence, the whole number of 0.5 will be 1.

How do you round off 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 you round to the nearest 5 in JavaScript?

To round a number to the nearest 5, call the Math. round() function, passing it the number divided by 5 and multiply the result by 5 .

How do you round 2 decimals 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.


Write your own function that multiplies by 2, rounds, then divides by 2, e.g.

function roundHalf(num) {
    return Math.round(num*2)/2;
}

Here's a more generic solution that may be useful to you:

function round(value, step) {
    step || (step = 1.0);
    var inv = 1.0 / step;
    return Math.round(value * inv) / inv;
}

round(2.74, 0.1) = 2.7

round(2.74, 0.25) = 2.75

round(2.74, 0.5) = 2.5

round(2.74, 1.0) = 3.0


Just a stripped down version of all the above answers:

Math.round(valueToRound / 0.5) * 0.5;

Generic:

Math.round(valueToRound / step) * step;

To extend the top answer by newtron for rounding on more than only 0.5

function roundByNum(num, rounder) {
    var multiplier = 1/(rounder||0.5);
    return Math.round(num*multiplier)/multiplier;
}

console.log(roundByNum(74.67)); //expected output 74.5
console.log(roundByNum(74.67, 0.25)); //expected output 74.75
console.log(roundByNum(74.67, 4)); //expected output 76


Math.round(-0.5) returns 0, but it should be -1 according to the math rules.

More info: Math.round() and Number.prototype.toFixed()

function round(number) {
    var value = (number * 2).toFixed() / 2;
    return value;
}