Home » Html » Javascript roundoff number to nearest 0.5

# Javascript roundoff number to nearest 0.5

Questions:

Can someone give me an idea how can i round off a number to the nearest 0.5.
I have to scale elements in a web page according to screen resolution and for that i can only assign font size in pts to 1, 1.5 or 2 and onwards etc.

If i round off it rounds either to 1 decimal place or none.
How can i accomplish this job?

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

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

Questions:

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

Questions:

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

and Number.prototype.toFixed()

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

Questions:
``````var f = 2.6;