0

Hello Coders, I am expecting 1.1 by this code "print(1.2-0.1)" but the result is 1.9999999999..., What is wrong Coders?

3rd Jan 2022, 5:12 PM
Aman Programmer
Aman Programmer - avatar
3 Réponses
+ 2
This is because, in python, 0.1 is not exactly 0.1. if you print 0.1 with 60 decimal point, you will see what I mean. ``` print(f"{0.1:.60f}") ``` The code above will show you that 0.1 is not precisely 0.1 but it much bigger that the actual value. Or you can use Decimal from decimal module to see the actual value for each floating number. For example: ``` from decimal import Decimal print(Decimal(0.1)) ``` So one of the solution is to use round() function. ``` a = 1.2 b = 0.1 r = round(a-b, 2) # we round off our result on 2 decimal places print(r) ```
3rd Jan 2022, 5:40 PM
Shahrull Fytri
Shahrull Fytri - avatar
+ 1
Wikipedia covers the floating point atithmetics pretty well https://en.m.wikipedia.org/wiki/Floating-point_arithmetic
3rd Jan 2022, 8:02 PM
Michal Doruch
0
Thanks for replying but i solved it.
4th Jan 2022, 3:16 AM
Aman Programmer
Aman Programmer - avatar