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:
BigDecimal
in Java), ordecimal
in C#).So, what library or solution exists for working with decimal values? Thanks!
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.
JavaScript has only one type of number. Numbers can be written with or without decimals.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With