Round a Floating Point Number Down to the Nearest Integer?

前端 未结 12 1432
悲哀的现实
悲哀的现实 2020-12-02 13:45

As the title suggests, I want to take a floating point number and round it down to the nearest integer. However, if it\'s not a whole, I ALWAYS want to round down the variab

相关标签:
12条回答
  • 2020-12-02 14:34

    One of these should work:

    import math
    math.trunc(1.5)
    > 1
    math.trunc(-1.5)
    > -1
    math.floor(1.5)
    > 1
    math.floor(-1.5)
    > -2
    
    0 讨论(0)
  • 2020-12-02 14:36

    If you don't want to import math, you could use:

    int(round(x))

    Here's a piece of documentation:

    >>> help(round)
    Help on built-in function round in module __builtin__:
    
    round(...)
        round(number[, ndigits]) -> floating point number
    
        Round a number to a given precision in decimal digits (default 0 digits).
        This always returns a floating point number.  Precision may be negative.
    
    0 讨论(0)
  • 2020-12-02 14:40

    I think you need a floor function :

    math.floor(x)

    0 讨论(0)
  • 2020-12-02 14:41

    Simple

    print int(x)
    

    will work as well.

    0 讨论(0)
  • 2020-12-02 14:42
    x//1
    

    The // operator returns the floor of the division. Since dividing by 1 doesn't change your number, this is equivalent to floor but no import is needed. Notes:

    1. This returns a float
    2. This rounds towards -∞
    0 讨论(0)
  • 2020-12-02 14:44

    I used this code where you subtract 0.5 from the number and when you round it, it is the original number rounded down.

    round(a-0.5)

    0 讨论(0)
提交回复
热议问题