Javascript - Cash Calculation

I have a page on the site that calculates the final rental rates, which are optional. Javascript serves nothing but to show you the updated amount if you select or deselect the checkboxes.

Here is what I have tried. It seems to work, but it adds 2 cents to every other click for one of the flags, I think, because for the rounds. How can I keep the number from rounding?

function update_rate(state, amount, field) { if (state == true) { rate = parseFloat($('span.rateTotal').text()) + amount; rate = rate.toFixed(2); due = parseFloat($('span.'+field).text()) + amount; due = due.toFixed(2); $('span.rateTotal').text(rate); $('span.'+field).text(due); } else { rate = parseFloat($('span.rateTotal').text()) - amount; rate = rate.toFixed(2); due = parseFloat($('span.'+field).text()) - amount; due = due.toFixed(2); $('span.rateTotal').text(rate); $('span.'+field).text(due); } } 

HTML checkbox:

 <cfinput type="checkbox" name="linen_service" id="linen_service" checked="checked" value="0" onClick="update_rate(this.checked, #reservationQuery[7].xmlChildren[i]['dblAmount'].xmlText#, 'second-due');" /> 

Basically conveys the number of options, the state of the flag, and the name of the field that should be affected.

Edit: Fiddle URL: http://jsfiddle.net/nGrVf/6/

+4
source share
2 answers

Are you stuck with your types?

I believe that it is almost always better to store monetary values ​​in integers of the lowest unit (for example, cents or pence), and then add a decimal point to two places on the right when displayed.

Thus, the transformations may look like this:

 var dollars = 100.43; var cents = Math.round(dollars * 100); //convert for display var sCents = String(cents); var display = sCents.substr(0, sCents.length-2) + "." + sCents.substr(sCents.length-2,2); alert(display); 

Here you can see http://jsfiddle.net/jameswiseman76/jhjtP/

Then you don't need to worry about any ugly floating point conversions.

+1
source

The simplest solution I can come up with is to round it (using muls and floor ): i.e.

 rate = Math.floor(rate * 100)/100; 

Edit: After a little testing, I found that there is nothing wrong with this code. This means that the calculation error comes from another part of the code or from an unknown amount variable.

0
source

Source: https://habr.com/ru/post/1346562/


All Articles