Rounding Numbers

 

Round

round(number, digits(optional))
Rounds the float value to the given number of decimal digits.

digits
-> define the number of decimal digits to be considered for rounding.

  • when not specified default is

    0

Code

a = round(3.14,1)
print(a)
a = round(3.14)
print(a)
PYTHON

Output

3.1
3

Floating Point Approximation

Float values are stored approximately.

Code

print(0.1 + 0.2)

Output

0.30000000000000004

Floating Point Errors

Sometimes, floating point approximation gives unexpected results.

Code

print((0.1 + 0.2) == 0.3)
PYTHON

Output

False

To avoid these unexpected results, we can use

round()

Code

a = round((0.1 + 0.2), 1)
print(a)
print(a == 0.3)
PYTHON

Output

0.3
True

Comments

Comment starts with a hash

#

It can be written in its own line next to a statement of code.

Code

n = 5
# Finding if Even
even = (n % 2 == 0)
print(even) # prints boolean value
PYTHON

Output

False

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form