As many of us know python has a specific way of adding two decimals. For example, when we run 0.1 + 0.2
in python, it will return something like 0.30000000000000004
. I forgot how to fix this problem unfortunately. Can you help me?
Asked
Active
Viewed 20 times
0

Stqrosta
- 352
- 2
- 10
-
It's not really specific to python. This happens pretty much with all languages that manipulate floating-point numbers. Floating-point numbers use binary, not decimal. Just like 1/3 cannot be represented exactly in decimal, 0.1 and 0.2 cannot be represented exactly in binary. There are many workarounds. One possibility might be to use fixed-point instead of floating-point. In python, you could use [module decimal](https://docs.python.org/3/library/decimal.html). – Stef Nov 10 '21 at 14:28
-
Another possibility is simply to keep using floating-point, but when calling function `print` to display the numbers, format the display to only show up to a certain number of places. Internally, the result will still be `0.30000000000000004` rather than `0.30000000000000000`, but when printing you'll truncate the display to only a few places, for instance `0.30`. – Stef Nov 10 '21 at 14:29
-
Possible duplicate: [How to format a floating-point number to fixed-width in python](https://stackoverflow.com/questions/8885663/how-to-format-a-floating-number-to-fixed-width-in-python) – Stef Nov 10 '21 at 14:31