Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript round up to nearest .5 [duplicate]

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 
like image 464
user3117628 Avatar asked Dec 06 '22 00:12

user3117628


1 Answers

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
like image 148
p.s.w.g Avatar answered Dec 27 '22 23:12

p.s.w.g