Limiting floats to two decimal points

前端 未结 28 3196
你的背包
你的背包 2020-11-21 04:57

I want a to be rounded to 13.95.

>>> a
13.949999999999999
>>> round(a, 2)
13.949999999999999

The ro

相关标签:
28条回答
  • 2020-11-21 05:20
    float_number = 12.234325335563
    round(float_number, 2)
    

    This will return;

    12.23
    

    round function takes two arguments; Number to be rounded and the number of decimal places to be returned.Here i returned 2 decimal places.

    0 讨论(0)
  • 2020-11-21 05:21

    You can modify the output format:

    >>> a = 13.95
    >>> a
    13.949999999999999
    >>> print "%.2f" % a
    13.95
    
    0 讨论(0)
  • 2020-11-21 05:21

    We multiple options to do that : Option 1:

    x = 1.090675765757
    g = float("{:.2f}".format(x))
    print(g)
    

    Option 2: The built-in round() supports Python 2.7 or later.

    x = 1.090675765757
    g =  round(x, 2)
    print(g)
    
    0 讨论(0)
  • 2020-11-21 05:22

    The method I use is that of string slicing. It's relatively quick and simple.

    First, convert the float to a string, the choose the length you would like it to be.

    float = str(float)[:5]
    

    In the single line above, we've converted the value to a string, then kept the string only to its first four digits or characters (inclusive).

    Hope that helps!

    0 讨论(0)
  • 2020-11-21 05:23

    Try the code below:

    >>> a = 0.99334
    >>> a = int((a * 100) + 0.5) / 100.0 # Adding 0.5 rounds it up
    >>> print a
    0.99
    
    0 讨论(0)
  • 2020-11-21 05:25

    In Python 2.7:

    a = 13.949999999999999
    output = float("%0.2f"%a)
    print output
    
    0 讨论(0)
提交回复
热议问题