Search code examples
javascriptfloating-accuracy

Round float values in JavaScript


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.


Solution

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

    (Math.floor(y/x) * x).toFixed(2);