0

I am trying to round my figure in JavaScript if it is less then any 0.5 figure. For Instance if I have value 3.4 then it should be 3 but if 3.5 then there is no need to round figure. I only want to round figure if it is less than 0.5. Here is the code I am using to round figure. But it rounded the figure in both cases

This code gives me result 3.5

function rounded(){
               var val = 3.5; 
                var rounded = Math.round(val);
                console.log("rounded",rounded);
}

and this code gives me result 4 but I want 3.5..

function rounded(){
                   var val = 3.6; 
                    var rounded = Math.round(val);
                    console.log("rounded",rounded);
    }

Any body can help me with this?

Vidya Sagar
  • 1,699
  • 3
  • 17
  • 28
Azad Chouhan
  • 87
  • 4
  • 13

2 Answers2

3

Use Math.floor to round down.

var round = function (num) {
   return Math.floor(num * 2) / 2;
};

console.log(round(3));  // 3
console.log(round(3.4));  // 3
console.log(round(3.5));  // 3.5
console.log(round(3.6));  // 3.5
console.log(round(4));  // 4
reergymerej
  • 2,371
  • 2
  • 26
  • 32
0

This should truncate to the nearest .5:

parseInt(x * 2) / 2;
ryachza
  • 4,460
  • 18
  • 28