BigDecimal in JavaScript

I am very new to JavaScript (I came from Java) and am trying to make some financial calculations with small amounts of money.

My initial version:

<script type="text/javascript"> var normBase = ("[price]").replace("$", ""); var salesBase = ("[saleprice]").replace("$", ""); var base; if (salesBase != 0) { base = salesBase; } else { base = normBase; } var per5 = (base - (base * 0.05)); var per7 = (base - (base * 0.07)); var per10 = (base - (base * 0.10)); var per15 = (base - (base * 0.15)); document.write ( '5% Off: $' + (Math.ceil(per5 * 100) / 100).toFixed(2) + '<br/>' + '7% Off: $' + (Math.ceil(per7 * 100) / 100).toFixed(2) + '<br/>' + '10% Off: $' + (Math.ceil(per10 * 100) / 100).toFixed(2) + '<br/>' + '15% Off: $' + (Math.ceil(per15 * 100) / 100).toFixed(2) + '<br/>' ); </script> 

This worked well, except it was always rounded ( Math.ceil ). Math.floor has the same problem, and Math.round also not suitable for floats.

In Java, I would completely avoid using floats from the very beginning, however in JavaScript, apparently, there is no default inclusion of something comparable.

The problem is that all the libraries mentioned are either broken, or for another purpose. The jsfromhell.com/classes/bignumber library jsfromhell.com/classes/bignumber very close to what I need, however I am having fancy problems with rounding and accuracy ... Regardless of what I installed Round Type, it seems that it solves by itself . So, for example, 3.7107 with an accuracy of 2 and a round type ROUND_HALF_UP somehow turns out to be 3.72, whereas it should be 3.71.

I also tried the @JasonSmith BigDecimal library (processed port from Java BigDecimal), but it seems to be for node.js, which I cannot run.

How can I do this using vanilla JavaScript (and be reliable), or is there a modern (mentioned above, which has been all years old) library that I can use that is supported and not broken?

+13
source share
1 answer

I like to use accounting.js to format numbers, money and currency.

Homepage - https://openexchangerates.imtqy.com/accounting.js/

Github - https://github.com/openexchangerates/accounting.js

+7
source

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