BigDecimal in JavaScript

匿名 (未验证) 提交于 2019-12-03 02:49:01

问题:

I'm very new to JavaScript (I come from a Java background) and I am trying to do some financial calculations with small amounts of money.

My original go at this was:

<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 always rounded up (Math.ceil). Math.floor has the same issue, and Math.round is also no good for floats.

In Java, I would have avoided the use of floats completely from the get-go, however in JavaScript there does not seem to be a default inclusion of something comparable (OMG WHY!?!?!?!).

So, my SO-fu has led me to this post: https://stackoverflow.com/questions/744099/is-there-a-good-javascript-bigdecimal-library

The problem is, all the libraries mentioned are either broken or for a different purpose. The jsfromhell.com/classes/bignumber library is very close to what I need, however I'm having bizarre issues with its rounding and precision... No matter what I set the Round Type to, it seems to decide on its own. So for example, 3.7107 with precision of 2 and round type of ROUND_HALF_UP somehow winds up as 3.72 when it should be 3.71.

I also tried @JasonSmith BigDecimal library (a machined port from Java's BigDecimal), but it seems to be for node.js which I don't have the option of running.

How can I accomplish this using vanilla JavaScript (and be reliable) or is there a modern (ones mentioned above are all years old now) library that I can use that is maintained and is not broken?

回答1:

I like using accounting.js for number, money and currency formatting.

Homepage - https://openexchangerates.github.io/accounting.js/

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!