Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Decimal Values

Tags:

What can I use as a decimal type in JavaScript? It's not supported (0.1 + 0.2 !== 0.3), and I need it for representing exact values in a banking/financial application. See The State and Future of JavaScript for a good read and the dirty details behind JavaScript and it's (lack of) support for decimal arithmetic.

By "decimal", I mean either:

  1. infinite-range and arbitrary-precision (like BigDecimal in Java), or
  2. limited range and precision, but suitable for financial calculations (like decimal in C#).

So, what library or solution exists for working with decimal values? Thanks!

like image 307
Mr. X Avatar asked Aug 11 '10 02:08

Mr. X


People also ask

How do I get 2 decimal places in JavaScript?

Use the toFixed() method to format a number to 2 decimal places, e.g. num. toFixed(2) . The toFixed method takes a parameter, representing how many digits should appear after the decimal and returns the result.

Can you use decimals in JavaScript?

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

How do you display decimals in JavaScript?

Use the toFixed() method in JavaScript to format a number with two decimals. The toFixed() method formats a number with a specific number of digits to the right of the decimal.


1 Answers

It is often recommended1 to handle money as an integer representing the number of cents: 2572 cents instead of 25.72 dollars. This is to avoid the problems with floating-point arithmetic that you mention. Fortunately integer arithmetic in floating point is exact, so decimal representation errors can be avoided by scaling.


1Douglas Crockford: JavaScript: The Good Parts: Appendix A - Awful Parts (page 105).

like image 132
Daniel Vassallo Avatar answered Oct 10 '22 01:10

Daniel Vassallo