How can I round a number up to the nearest .5? For example:
5.4 -> 5.5
5.6 -> 6
6.1 -> 6.5
Here is what I tried so far:
var number = 5.1;
var roundednumber = Math.round(number*2)/2
That's what the Math.ceil
(ceiling) method is for:
The
Math.ceil(x)
function returns the smallest integer greater than or equal to a number "x".
For example:
var number = 5.1;
var roundednumber = Math.ceil(number*2)/2; // 5.5
But note that it will also round negative numbers up (more positive):
var number = -5.1;
var roundednumber = Math.ceil(number*2)/2; // -5
If you want to round away from 0, you'd have to do something like this:
var number = -5.1;
var roundednumber = (number > 0 ? Math.ceil : Math.floor)(number*2)/2; // -5.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With