Skip to content Skip to sidebar Skip to footer

Javascript: Rounding A Float Up To Nearest .25 (or Whatever...)

All answers I can find are rounding to nearest, not up to the value... for example 1.0005 => 1.25 (not 1.00) 1.9 => 2.00 2.10 => 2.25 2.59 => 2.75 etc. would seem

Solution 1:

Divide the number by 0.25 (or whatever fraction you want to round nearest to).

Round up to nearest whole number.

Multiply result by 0.25.

Math.ceil(1.0005 / 0.25) * 0.25// 1.25

Math.ceil(1.9 / 0.25) * 0.25// 2// etc.

functiontoNearest(num, frac) {
  returnMath.ceil(num / frac) * frac;
}

var o = document.getElementById("output");

o.innerHTML += "1.0005 => " + toNearest(1.0005, 0.25) + "<br>";
o.innerHTML += "1.9 => " + toNearest(1.9, 0.25) + "<br>";
o.innerHTML += "2.10 => " + toNearest(2.10, 0.25) + "<br>";
o.innerHTML += "2.59 => " + toNearest(2.59, 0.25);
<divid="output"></div>

Solution 2:

Multiply the number by 4, use Math.ceil on the result and then divide that number by 4.

Solution 3:

Just multilpy by 4 and take the ceiled value with 4 times.

var values = [1.0005, 1.9, 2.10, 2.59],
    round = values.map(function (a) { returnMath.ceil(a * 4) / 4; });

document.write('<pre>' + JSON.stringify(round, 0, 4) + '</pre>');

Solution 4:

Other divide and multiply will not work for some values such as 1.59 You can try customRound function

functioncustomRound(x) {
    var rest = x - Math.floor(x)

    if (rest >= 0.875) {
        returnMath.floor(x) + 1
    } elseif (rest >= 0.625) {
        returnMath.floor(x) + 0.75
    } elseif (rest >= 0.375) {
        returnMath.floor(x) + 0.50
    }  elseif (rest >= 0.125){
        returnMath.floor(x) + 0.25
    } else {
        returnMath.floor(x)
    }
}

Post a Comment for "Javascript: Rounding A Float Up To Nearest .25 (or Whatever...)"