Reputation: 8225
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.
Upvotes: 0
Views: 1014
Reputation: 1
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
Upvotes: 0
Reputation: 16861
The solution is in another question already asked: Dealing with float precision in Javascript
(Math.floor(y/x) * x).toFixed(2);
Upvotes: 3