Search code examples
javascriptrounding

how to do round half even in javascript unlimited digits after point?


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


Solution

  • Edit: I cannot delete accepted answer.

    Please do not use this code. Use Gaussian/banker's rounding in JavaScript instead.

    function roundHalfToEven(num, precision) {
      const mult = 10 ** precision;
      const multiplied = num * mult
      const rounded = Math.round(multiplied)
      const isTie = 10*(multiplied - Math.trunc(multiplied)) === 5
      
      // console.log(isTie, multiplied, Math.trunc(multiplied))
      
      if (!isTie) {
        return rounded/mult
      }
      
      return  (rounded%2 === 0 ? rounded : rounded - 1)/mult;
    }
    
    const cases = [
      [23.35, 1, 23.4],
      [24.45, 1, 24.4],
      [24.46, 1, 24.5],
      [24.44, 1, 24.4]
    ]
    
    for (const [num, precision, result] of cases) {
      console.assert(roundHalfToEven(num, precision) === result, `Expected ${num} rounded to ${precision} to equal ${result}, got ${roundHalfToEven(num, precision) }`)
    }
    
    console.log('Success')