+ 3

What are some best practices in regard to accurately calculating monetary values in JavaScript?

When working with 4 function math to calculate percentages and subtotals on monetary values, what are some of the best practices to ensure accuracy down to the penny? Thanks!

5th Feb 2020, 3:15 AM
Lisa F
Lisa F - avatar
6 ответов
+ 4
Lisa F If you are prioritizing accuracy over speed, you could also consider a library like decimal.js: https://mikemcl.github.io/decimal.js/ https://github.com/MikeMcl/decimal.js/blob/master/README.md
5th Feb 2020, 9:54 AM
David Carroll
David Carroll - avatar
+ 4
Lisa F Unfortunately, there isn't anything basic about it in a dynamic language that supports one type for number, which happens to be a double float. In C#, a decimal type is much slower than using a float as the arithmetic involves base 10 operations at a high level that eventually get converted to base 2 for binary operations at compile time. (I think most of that is accurate. Just going from memory here.) The point is, while decimal is much slower, it's much, much, much more accurate, and for reasons that would be too involved to discuss here. To explore this further, it's important to have a strong understanding of IEEE 754 standards for floating point arithmetic and the challenges of representing base 10 fractions as base 2 values on 32bit vs 64 bit CPU architecture. The are hacks that could work in some arithmetic use cases. But these would be far from best practices. I highly recommend reviewing this source code as a good start: https://github.com/MikeMcl/decimal.js/blob/master/decimal.js
6th Feb 2020, 1:08 AM
David Carroll
David Carroll - avatar
+ 4
Lisa F I also recommend you read the question linked below on a somewhat related topic regarding float behavior differences between the following: 0.9999999999999999 (16 digits) vs 0.99999999999999999 (17 digits) Be sure to sort by date and really digest the various responses. You'll begin to appreciate how complex this can be to even talk about even among some really sharp people here. https://www.sololearn.com/Discuss/2149084/
6th Feb 2020, 1:18 AM
David Carroll
David Carroll - avatar
+ 3
Lisa F I updated my earlier response to include a link to the Readme.md file - which I think is worth reading to see how decimal.js compares to similar libraries and then review usage examples.
5th Feb 2020, 3:13 PM
David Carroll
David Carroll - avatar
+ 3
thanks David Carroll and Calviղ ..would love to have some basic tips that do not involve extra libraries too. ty
5th Feb 2020, 10:15 PM
Lisa F
Lisa F - avatar
+ 2
Use a library valled moneysafe to avoid floating point error. More information https://github.com/ericelliott/moneysafe
5th Feb 2020, 6:57 AM
Calviղ
Calviղ - avatar