andreibyf/Data-Science-Articles

A Beginner’s Guide to Decimal Points in Python

Opened this issue · 0 comments

Summary

A Beginner’s Guide to Decimal Points in Python

Author

Jonathan Hsu

Link

https://levelup.gitconnected.com/a-beginners-guide-to-decimal-points-in-python-467c36d2a85a

Key Takeaways

  • Rounding
  • Truncating
  • Printing Decimals

Code Snippet

#five and up rule
myNum = 3.14159265359
print(round(myNum,2) # 3.14
print(round(myNum,4) # 3.1416

#round up
from math import ceil
myNum = 3.14159265359
print(ceil(myNum)) # 4

#round down
from math import floor
myNum = 3.14159265359
print(floor(myNum)) # 3

#truncate
from math import trunc
myNum = 3.14159265359
print(trunc(myNum)) # 3

#truncate decimals
from math import trunc
def truncate(n,d=0):
if d>0:
return trunc(n * 10d) / (10d)
else:
return trunc(n)
myNum = 3.14159265359
print(truncate(myNum)) # 3
print(truncate(myNum,4)) # 3.1415

#printing decimals
myNum = 3.14159265359
myNum = round(myNum,2)
print(f"My number is {myNum}") # My number is 3.14

#printing decimal and keeping original number
myNum = 3.14159265359
print(f"My number is {round(myNum,2)}") # My number is 3.14

Custom Code

Images

Comments/Questions

Quick and simple guide to kick-off your decimal values. Need more to mastering decimals, including understanding floating-point numbers and using advanced tools such as the Decimal class.

Useful Tools