Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any good JavaScript currency or decimal classes?

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?

like image 855
Jeff Davis Avatar asked May 11 '11 16:05

Jeff Davis


People also ask

Can you use decimals in JavaScript?

JavaScript has only one type of number. Numbers can be written with or without decimals.

Which data type in JavaScript should be used to represent monetary values?

You can use libraries like Decimal. js that will handle your floats as strings. This isn't a bad solution and even comes handy when you have to handle big numbers.

Does JavaScript use floating point math?

JavaScript supports one mathematical type, 64-bit floating point numbers.

What is js currency?

currency. js is a lightweight ~1kb javascript library for working with currency values. It was built to work around floating point issues in javascript. This talk by Bartek Szopka explains in detail why javascript has floating point issues.


1 Answers

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).

like image 95
Lightness Races in Orbit Avatar answered Oct 17 '22 07:10

Lightness Races in Orbit