Round number to nearest integer

前端 未结 11 2132
傲寒
傲寒 2020-11-27 12:32

I\'ve been trying to round long float numbers like:

32.268907563;
32.268907563;
31.2396694215;
33.6206896552;
...

With no success so far. I

11条回答
  •  青春惊慌失措
    2020-11-27 13:04

    Your solution is calling round without specifying the second argument (number of decimal places)

    >>> round(0.44)
    0
    >>> round(0.64)
    1
    

    which is a much better result than

    >>> int(round(0.44, 2))
    0
    >>> int(round(0.64, 2))
    0
    

    From the Python documentation at https://docs.python.org/3/library/functions.html#round

    round(number[, ndigits])

    Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

    Note

    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.

提交回复
热议问题