Javascript roundoff number to nearest 0.5


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?

Answers:

Answer

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

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

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

More info: Math.round() and Number.prototype.toFixed()

function round(number) {
    var value = (number * 2).toFixed() / 2;
    return value;
}
Answer
var f = 2.6;
var v = Math.floor(f) + ( Math.round( (f - Math.floor(f)) ) ? 0.5 : 0.0 );
Answer

To extend the top answer by newtron for rounding on more than only 0.5

function roundByNum(num, rounder) {
    var multiplier = 1/(rounder||0.5);
    return Math.round(num*multiplier)/multiplier;
}

console.log(roundByNum(74.67)); //expected output 74.5
console.log(roundByNum(74.67, 0.25)); //expected output 74.75
console.log(roundByNum(74.67, 4)); //expected output 76

Answer

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

Answer
    function roundToTheHalfDollar(inputValue){
      var percentile = Math.round((Math.round(inputValue*Math.pow(10,2))/Math.pow(10,2)-parseFloat(Math.trunc(inputValue)))*100)
      var outputValue = (0.5 * (percentile >= 25 ? 1 : 0)) + (0.5 * (percentile >= 75 ? 1 : 0))
      return Math.trunc(inputValue) + outputValue
    }

I wrote this before seeing Tunaki's better response ;)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.