Rounding integers? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
0

Rounding integers?

Why is the result of x = 4.9999999999999999 y = int(x) print(y) 5 but the result of x = 4.999999999999999 y = int(x) print(y) 4 ? Edit: Second question: Is there one single thing you can use instead of int() to work only with mathematically correctly rounded numbers? (I know I could google it, but I'm taking it easy with Sololearn course. tnx in advance). Edit2: So now I know round() exists. z = round(x) print(z) = 5

31st Oct 2021, 10:14 AM
Jona Žonta
Jona Žonta - avatar
2 Antworten
+ 6
It's a matter of floating point precision. Python deals 17 significant digits after floating point. https://docs.python.org/3/tutorial/floatingpoint.html
31st Oct 2021, 10:18 AM
Lisa
Lisa - avatar
+ 2
If you want rounding, and not truncation, why aren't you using round()?
31st Oct 2021, 12:45 PM
Steve
Steve - avatar