Our great sponsors
-
Basenumber.js
A BigDecimal library for arbitrary precision that allows you to work with numbers in different bases from 2 to 36.
-
SurveyJS
Open-Source JSON Form Builder to Create Dynamic Forms Right in Your App. With SurveyJS form UI libraries, you can build and style forms in a fully-integrated drag & drop form builder, render them in your JS app, and store form submission data in any backend, inc. PHP, ASP.NET Core, and Node.js.
That's because every number in JavaScript is represented using 64 bits floating point. Since numbers are saved in binary, there are some decimal numbers that are periodics in binary but not in decimal, e.g. 0.2, equivalent to 0.00110011001100110011... in bin. You can avoid this using some BigDecimals libraries like decimal.js, or, if you need to work in different bases, you have Basenumber.js
That's because every number in JavaScript is represented using 64 bits floating point. Since numbers are saved in binary, there are some decimal numbers that are periodics in binary but not in decimal, e.g. 0.2, equivalent to 0.00110011001100110011... in bin. You can avoid this using some BigDecimals libraries like decimal.js, or, if you need to work in different bases, you have Basenumber.js
Obviously it's a disaster for financial calculations where accuracy is absolutely paramount, so for this you should be using integers/bigint and working in cents/pence, or use a package like BigNumber.js.
Related posts
- Decoding Why 0.6 + 0.3 = 0.8999999999999999 in JS and How to Solve?
- Solving the "floating point precision" problem with... floats?
- BigDecimal equivalent. What do you use?
- [AskJS] Are there numeric textbox widgets with built-in support for big numbers like decimal.js?
- Working with Currency Values in TypeScript