Photo by Jeswin Thomas on Unsplash
2 min read
The IEEE 754 Standard
console.log(0.1 + 0.2); // Output: 0.30000000000000004
This is because 0.1 and 0.2 cannot be accurately represented in the binary floating point format used by IEEE 754. When these numbers are converted to binary, they are rounded to the nearest approximation, which leads to the small error we see above.
If you require high precision and don't mind adding an external library to your project, you could use a library like decimal.js or bignumber.js. These libraries provide data types that can represent decimal values with higher precision than the native floating point data type.
If you need a quick and simple solution and don't mind losing some precision, you could use the
toFixedmethod to round the result to a specific number of decimal places.
If you need a solution that is both fast and accurate and don't mind doing extra calculations, you could use fixed-point arithmetic. Representing decimal values as integers, by scaling them up by a certain factor, can help to avoid precision errors.
If you require great precision and don't mind using an external library in your project, this is a viable option.
import Decimal from 'decimal.js'; console.log(new Decimal(0.1).plus(new Decimal(0.2)).toNumber()); // Output: 0.3
This is a quick and easy method that is adequate for many applications, but it may not be ideal if great accuracy is required.
console.log((0.1 + 0.2).toFixed(2)); // Output: 0.30 console.log(Math.round(0.1 + 0.2)) // Output: 0
Using fixed-point arithmetic
This is appropriate for circumstances requiring both speed and accuracy. However, if you need to work with very large numbers, the scaling factor may cause the numbers to become too enormous to represent effectively.
const precision = 1000 console.log((0.1 * precision + 0.2 * precision) / precision) // Output: 0.3
Finally, the ideal solution will be determined by your specific needs and the trade-offs you are ready to make.