How to properly truncate a float/decimal to a specific place after the decimal in python? -
in python 2.7.3, current behavior:
>>> 8./9. 0.8888888888888888 >>> '%.1f' % (8./9.) '0.9'
same appears true decimal
s:
>>> decimal import decimal >>> decimal(8) / decimal(9) decimal('0.8888888888888888888888888889') >>> '%.1f' % (decimal(8) / decimal(9)) '0.9'
i have expected truncation, however, appears round. options truncating tenths place?
fyi ask because current solution seems hacky (but maybe best practice?) make string of result, finds period , finds x digits after period want.
so options truncating tenths place?
the decimal.quantize() method rounds number fixed exponent , provides control on rounding mode:
>>> decimal import decimal, round_floor >>> decimal('0.9876').quantize(decimal('0.1'), rounding=round_floor) decimal('0.9')
don't use math.floor on decimal values because first coerces them binary float introducing representation error , lost precision:
>>> x = decimal('1.999999999999999999998') >>> x.quantize(decimal('0.1'), rounding=round_floor) decimal('1.9') >>> math.floor(x * 10) / 10 2.0
Comments
Post a Comment