yandex
loader

please wait

  • Dipti Singh Mar-11-2019 07:37:58 AM ( 2 months ago )

    I am having an issue with the way Javascript is rounding numbers when hitting 0.5. I am writing levies calculators, and am noticing a 0.1c discrepancy in the results.

    The problem is that the result for them is 21480.705 which my application translates into 21480.71, whereas the tariff says 21480.70.

    This is what I am seeing with Javascript:

    (21480.105).toFixed(2)
    "21480.10"
    (21480.205).toFixed(2)
    "21480.21"
    (21480.305).toFixed(2)
    "21480.31"
    (21480.405).toFixed(2)
    "21480.40"
    (21480.505).toFixed(2)
    "21480.51"
    (21480.605).toFixed(2)
    "21480.60"
    (21480.705).toFixed(2)
    "21480.71"
    (21480.805).toFixed(2)
    "21480.81"
    (21480.905).toFixed(2)
    "21480.90"

    Questions:

    • What the hell is going on with this erratic rouding?
    • What's the quickest easiest way to get a "rounded up" result (when hitting 0.5)?
     
  • Ekta Singhania Mar-11-2019 07:39:21 AM ( 2 months ago )

    This seems to do the trick.

    The rounding problem can be avoided by using numbers represented in exponential notation:

    function round(value, decimals) {
      return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
    }
    
    console.log(round(21480.105, 2).toFixed(2));

Please login

Similar Discussion

Recommended For You