Python float round error 117.285 round to 117.28 not 117.29

后端 未结 3 1682
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-10 17:47

I am using python 2.7, and the code I have is:

a = 10.5 * 22.34 / 2.0
print \"%.2f\" % a

and the result I expect is 117.29, but it shows 11

3条回答
  •  抹茶落季
    2020-12-10 18:32

    If you want a simple solution and don't care about performance, you could use a function like this to convert to integer, round, and convert back to float:

    def round_exact(number, decimal_places=0):
        """Round the number to the given number of decimal places by converting to 
        and from integers to avoid floating point error."""
        factor = 10**(decimal_places + 1)
        rounded_int = int(number * factor)
        if rounded_int % 10 >= 5:
            # Round up
            return (int(rounded_int//10) + 1) / float(factor//10)
        # Round down
        return int(rounded_int//10) / float(factor//10)
    

提交回复
热议问题