Python - Numeric Number truncation

Introduction

The following code shows how to do number truncation:

Demo

import math 

print( math.floor(3.567), math.floor(-2.567) )         # Floor (next-lower integer) 
print( math.trunc(3.567), math.trunc(-2.567) )         # Truncate (drop decimal digits) 
print( int(2.567), int(-2.567) )                       # Truncate (integer conversion) 
print( round(2.567), round(2.467), round(2.567, 2) )   # Round (Python 3.X version) 
print( '%.1f' % 2.567, '{0:.2f}'.format(2.567) )       # Round for display (Chapter 7) 
print( (1 / 3.0), round(1 / 3.0, 2), ('%.2f' % (1 / 3.0)) )

Result

Related Topic