Search code examples
javascriptjqueryajaxcurrency

Should I do money calculations in Javascript or as an AJAX call?


I'm building a webapp using JQuery, Stripes, Spring and JPA (Hibernate).

I have a page that allows users to enter a number of order line items and each time onblur occurs in the price field, I have a JQuery event bound to the field which sums all the price fields (this is a subtotal), calculates 10% tax and adds the tax to the subtotal. I update the page to display the subtotal, tax and grand total.

My question is, should I be doing this calculation in Javascript? If so, how can I be sure the rounding etc is working correctly? I'm a bit worried about problems with precision.

Would it be better for me to make an Ajax call to do the calculation in Java?

Any advice would be great!


Solution

  • As a rule of thumb, you need to measure what's important for your application. If it's absolute precision then do it as an AJAX call because there may be rounding differences between browsers, computers and OS.

    When I was developing a site for a company I was working for I had the same problem, however we manage to use the javascript part by using a clever twist by using only integer arithmetics.

    Because we were dealing with currency with two digits, we multiplied everything by 10,000 and did the calculations. Rounding up to the integer and divided by 10,000 truncating the result to two decimal places.

    That make the round-trips nicely and consistently between the browser and the server side.