Are there any good javascript currencies or decimal classes?

I am trying to deal with JavaScript values ​​such as 23.45, but I want to be able to perform mathematical operations on these values ​​(addition, subtraction, multiplication, division) without using floating point problems. Yes, I sometimes need to round results, but I would like them to give reasonable answers.

Consider this in javascript:

24.56 * .3 

Productivity

 7.36799999999 

I would like it to come out with 7.368.

Most languages ​​have a decimal or currency type to handle this. Has anyone created a class that can handle this kind of data efficiently, or is there any other solution for working with these types of numbers without constantly correcting floating point errors?

+6
source share
6 answers

Instead of using integers (which have their own problems)

I would use the bignumber.js library

+2
source

type Integer.

No need to use floating point for currency. Use a fixed point where the number of decimal points is 0.

You count in pennies (or perhaps in tenths).

+11
source

There is a Math

The Math object is built into the JavaScript specification, so every browser has it natively.

Regarding data types, JavaScript has Number . It. We do not have another type of data data. It is best to think in order to try to work with integers.

+2
source

Carrying out a few more searches, I came across this.

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

None of them seem to be perfect, but they do the job.

+1
source

ku4jQuery-kernel contains both a money class and a math utility that contains operations and rounding, including round, roundUp and roundDown. These are good methods because you can pass a value to round to. For example, you can do $ .math.round (3.4567, -2) and it will round the number 3.4567 to the nearest 10 ^ -2. The same goes for money. $ .money (100.87) .divide (2) .roundUp (). toString () will give "$ 50.44". You can go further and add money denomination as a second parameter, for example, β€œB” for bitcoins, $ .money (100.87, β€œB”). Divide (2) .roundUp (). ToString (). You can find more information about this library here ku4jQuery-kernel and other libraries that may be useful here kodmunki github . These libraries are closely supported and used in many production projects. If you decide to try them, I hope you find them useful! Happy coding: {)}

+1
source

New guy on the block: moneysafe . It is open source and takes a functional approach that allows smart composition.

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

https://github.com/ericelliott/moneysafe

+1
source

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


All Articles