3

I want to have 26.955 rounded to 26.96

I mean if I have numbers 0-4 I want to round them down and if they are 5-9 I want to round them up

I considered parseFloat(number).toFixed(2) however it returns me 26.95, I need 26.96 I used Math.round but this doesn't work either, I saw Math.round10 but it told me this function doesn't exist so I don't know how to solve my problem.

UPDATE: I don't have always 3 digits after point I have more than that I would have 26.956736489

your mentioned duplicate talks about .fixed(2) I am saying it is not working for half even it is not a duplicate

Nickool
  • 3,662
  • 10
  • 42
  • 72

2 Answers2

-2

Try

Math.round(29.955*100)/100; //29.96

Or cool functional approach

function round(n) {
   n = Math.pow(10,n);
   return function(num) {
       return Math.round(num*n)/n;
   }
}

var round2 = round(2);
var num = 29.9555;
console.log(round2(num));
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • its not doing it for 17.955 i am just so surprised :O why?! but it is doing it for 29.9555 – Nickool Nov 10 '14 at 18:39
  • 5
    This is wrong. `Math.round()` doesn't do half even rounding but instead always rounds up on a tie so it has a bias. – billc.cn Oct 31 '17 at 10:32
  • This will not round half even https://en.wikipedia.org/wiki/Rounding#Round_half_to_even – radulle Oct 12 '22 at 05:54
-2

use this:

var num=26.955
Math.round(num* 100) / 100;
Mukund Kumar
  • 21,413
  • 18
  • 59
  • 79
  • this is my own question what are you talking about – Nickool Nov 07 '14 at 17:04
  • @Nick Didn't you notice that I posted it under *answer* and link was also to the *answer*? – nicael Nov 07 '14 at 17:19
  • yes I did but they answered only in 2 minutes it doesn't mean he cheated on someone else I don't know why stackoverflow became somewhere which I am not comfortable anymore – Nickool Nov 07 '14 at 17:21