0

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

  • See some answers here https://stackoverflow.com/questions/41383787/round-down-to-2-decimal-in-python and here https://stackoverflow.com/questions/8595973/truncate-to-three-decimals-in-python – Bran Nov 13 '20 at 00:48

1 Answers1

0

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.

Bryce
  • 111
  • 3
  • Had hoped to not round the number at all, but thank you for the response. – user1481421 Nov 14 '20 at 04:56
  • Unfortunately, there is no simple way to truncate to a number of decimal places. They all are similar to your method or potentially even more complicated for certain use cases. I feel like this would be a good feature to add to python. Perhaps allow `math.floor` and `math.celing` to take a number of decimal places. – Bryce Nov 15 '20 at 05:29