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 to be pretty basic, but this has me stumped. But this has to round up, not to nearest, which is a relatively easy thing to do.
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 to be pretty basic, but this has me stumped. But this has to round up, not to nearest, which is a relatively easy thing to do.
Share Improve this question asked Feb 25, 2016 at 21:59 ManiaqueManiaque 7611 gold badge8 silver badges23 bronze badges 2- 3 and what is the question? – Nina Scholz Commented Feb 25, 2016 at 22:00
- multiply by 4 => round => divide by 4 – R. Schifini Commented Feb 25, 2016 at 22:02
4 Answers
Reset to default 20Divide 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.
function toNearest(num, frac) {
return Math.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);
<div id="output"></div>
Multiply the number by 4, use Math.ceil on the result and then divide that number by 4.
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) { return Math.ceil(a * 4) / 4; });
document.write('<pre>' + JSON.stringify(round, 0, 4) + '</pre>');
Other divide and multiply will not work for some values such as 1.59 You can try customRound function
function customRound(x) {
var rest = x - Math.floor(x)
if (rest >= 0.875) {
return Math.floor(x) + 1
} else if (rest >= 0.625) {
return Math.floor(x) + 0.75
} else if (rest >= 0.375) {
return Math.floor(x) + 0.50
} else if (rest >= 0.125){
return Math.floor(x) + 0.25
} else {
return Math.floor(x)
}
}