Wednesday, May 13, 2015

round() - Python Tutorial


round() is a build-in function in the Python Programming Language which gives us the ability to round a floating point number to the closest multiple of 10. It is important to understand that round() function takes a floating point number which has been convert from a fraction so sometimes the round() may return some numbers a different than you expect.


round() Syntax


round(floating point number, numbers after the decimal)


Round() only takes floating point numbers which is our first argument and the second argument is how many numbers positions do you want after the decimal point. If you do not provide a second argument python will return a integer type number as the default.


round() Examples


#round() Examples

#round() with no second argument
>>> round(1.7)
2

#round() with an second argument of 1
>>> round(1.76, 1)
1.8

#round() example with an second argument of 4
>>> round(1.56787, 4)
1.5679

Weird Round() Returns


round(0.5) – returns 0 but we would expect this to return 1


round(2.675, 2) - returns 2.67 but in reality it should be 2.68.  Python returns 2.67 because this number is convert to a fraction and then converted back from a fraction and the conversion is not exact the actual return for 2.67 is 2.67499999999999982236431605997495353221893310546875



No comments:

Post a Comment