Good day all. Rather than calling the following every time to get ( in this case ) a two place decimal rendition of a float - is there a better ( more pythonic ) way?
def dec2( anum ) :
return( (math.trunc( anum*100))/ 100.0 )
Thanks, Al
Good day all. Rather than calling the following every time to get ( in this case ) a two place decimal rendition of a float - is there a better ( more pythonic ) way?
def dec2( anum ) :
return( (math.trunc( anum*100))/ 100.0 )
Thanks, Al
I believe that what you are looking for is the built-in round()
function. You can specify the number of decimal places. In your case, you want two decimal places, so you could simply call round(anum, 2)
. This is slightly different than what you are doing since you are truncating. The difference is that math.trunc(5.11999*100))/100.0==5.11
but round(5.11999,2)==5.12
.
There are some other technicalities on how the rounding works as well that you can read about if required for what you are doing.