Are there any good JavaScript currency or decimal

2020-07-02 10:46发布

I am trying to deal with JavaScript values such as 23.45, but I want to be able to do mathematical operations on these values (addition, subtraction, multiplication, division) without running into floating point issues. Yes, I might need to round the results sometimes, but I would like it to give reasonable answers.

Consider this in JavaScript:

24.56 * .3

Yields

7.36799999999

I would like it to come out with 7.368.

Most languages have either a decimal or currency data type to deal with this. Has anyone built a class that can handle this sort of data effectively, or is there any other solution for dealing with these sorts of numbers without having to constantly adjust for floating point errors?

7条回答
啃猪蹄的小仙女
2楼-- · 2020-07-02 11:30

Instead of using integers (which have their own problems)

I would use the bignumber.js library

查看更多
倾城 Initia
3楼-- · 2020-07-02 11:34

Integers.

There is no need to use floating-point for currency. Use fixed-point, where the number of decimal points is 0.

You count in pennies (or possibly in tenths of pennies).

查看更多
Luminary・发光体
4楼-- · 2020-07-02 11:34

New kid on the block: moneysafe. It's open-source, and uses a functional approach that allows smart composition.

$(.1) + $(.2) === $(.3).cents;

https://github.com/ericelliott/moneysafe

查看更多
叼着烟拽天下
5楼-- · 2020-07-02 11:41

The toFixed method can round to a given number of decimals.

There is also a Javascript sprintf implementation.

查看更多
家丑人穷心不美
6楼-- · 2020-07-02 11:44

There is Math

The Math object is build into the JavaScript spec so every browser has it natively.

As for data types, JavaScript has Number. That's it. We have no other number data type. The best think to do is to try and work with Integers.

查看更多
甜甜的少女心
7楼-- · 2020-07-02 11:48

Doing some more searching, I came across this.

https://stackoverflow.com/questions/744099/javascript-bigdecimal-library

It looks like none of them are ideal, but they do the job.

查看更多
登录 后发表回答