Why is Python's round so strange?

前端 未结 3 769
慢半拍i
慢半拍i 2020-12-31 11:24

My code:

  #!/usr/bin/python
  # -*- coding: utf-8 -*-
  print (round(1.555, 1))  # It seems normal
  print (round(1.555, 2))  # Why it is not output 1.56?
          


        
3条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 11:42

    Straight from the documentation:

    The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

提交回复
热议问题