0

I am trying to round a value in JS but I am getting not rounded value, this is what I have:

  $(document).on("click", ".open-AddBookDialog", function () {
              var agentPercentage = parseFloat($('#<%=ddlSplitPerc.ClientID%>').val()).toFixed(2);
              var percMod = 1.0 - agentPercentage;
              percMod = Math.ceil(percMod * 100) / 100;
              var dropdownAgentPerc = $('#<%=ddlPercSplitAgent.ClientID %>');
              dropdownAgentPerc.val(percMod);
             dropdownAgentPerc.change();           
             $('#AddNewSplitAgentLife').modal('show');
          });

For example, the agentPercentage is 0.7 and when I am subtracting 1 - 0.7 I am getting this value:

0.30000000000000004

What do you think I should change? I tried the Math.cell example as well but I am getting 0.31 as a result.

halfer
  • 19,824
  • 17
  • 99
  • 186
Laziale
  • 7,965
  • 46
  • 146
  • 262
  • So you're saying that you're surprised that floating point mathematics are not precise on a computer? – Tomalak Aug 13 '13 at 19:52
  • This tells you why you're getting that result: [Is JavaScript's Floating-Point Math Broken?](http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken) – bfavaretto Aug 13 '13 at 19:55

2 Answers2

3

The solution is in another question already asked: Dealing with float precision in Javascript

(Math.floor(y/x) * x).toFixed(2);
Community
  • 1
  • 1
jerone
  • 16,206
  • 4
  • 39
  • 57
  • thx for your answer but how can I utilize that formula in my case? I am not doing any dividing, I tried (Math.floor(1 - 0.7) * 1) but I am getting 0 as a result. Thanks – Laziale Aug 13 '13 at 19:59
  • 1
    You only need the `.toFixed(2)` part. – jerone Aug 13 '13 at 20:02
0

It should work if you subtract .5 from the value you pass to Math.ceil

percMod = Math.ceil((percMod * 100) -.5 )/ 100;

Math.ceil will round up for any decimal above .000

So to simulate the typical rounding behavior of only rounding decimals above .500 you should subtract .5