JavaScript 中的大十进制 [英] BigDecimal in JavaScript
问题描述
我对 JavaScript 非常陌生(我来自 Java 背景),我正在尝试用少量资金进行一些财务计算.
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.
我最初的做法是:
<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>
这很好用,只是它总是四舍五入(Math.ceil
).Math.floor
也有同样的问题,Math.round
也不适合浮点数.
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.
在 Java 中,我会从一开始就完全避免使用浮点数,但是在 JavaScript 中似乎没有默认包含类似的东西.
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.
问题是,所有提到的库要么已损坏,要么用于不同的目的.jsfromhell.com/classes/bignumber
库非常接近我的需要,但是我在舍入和精度方面遇到了奇怪的问题......无论我将 Round Type 设置为什么,它似乎是自己决定的.因此,例如,精度为 2 且圆形类型为 ROUND_HALF_UP
的 3.7107 在应该为 3.71 时以某种方式以 3.72 结束.
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.
我还尝试了@JasonSmith BigDecimal 库(来自 Java 的 BigDecimal 的机加工端口),但它似乎适用于我无法运行的 node.js.
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.
我如何使用 vanilla JavaScript(并且可靠)来实现这一点,或者是否有一个现代的(上面提到的那些现在都老了)我可以使用的库得到维护并且没有损坏?
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?
推荐答案
我喜欢使用 accounting.js
来格式化数字、货币和货币.
I like using accounting.js
for number, money and currency formatting.
主页 - https://openexchangerates.github.io/accounting.js/
Github - https://github.com/openexchangerates/accounting.js
这篇关于JavaScript 中的大十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!