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.

2
  • So you're saying that you're surprised that floating point mathematics are not precise on a computer? Commented Aug 13, 2013 at 19:52
  • This tells you why you're getting that result: Is JavaScript's Floating-Point Math Broken? Commented Aug 13, 2013 at 19:55

2 Answers 2

3

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

(Math.floor(y/x) * x).toFixed(2);
Sign up to request clarification or add additional context in comments.

2 Comments

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
You only need the .toFixed(2) part.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.