How to turn a float number like 293.4662543 into 293.47 in python?

邮差的信 提交于 2019-11-29 16:28:17

问题


How to shorten the float result I got? I only need 2 digits after the dot. Sorry I really don't know how to explain this better in English...

Thanks


回答1:


From The Floating-Point Guide's Python cheat sheet:

"%.2f" % 1.2399 # returns "1.24"
"%.3f" % 1.2399 # returns "1.240"
"%.2f" % 1.2 # returns "1.20"

Using round() is the wrong thing to do, because floats are binary fractions which cannot represent decimal digits accurately.

If you need to do calculations with decimal digits, use the Decimal type in the decimal module.




回答2:


If you want a number, use the round() function:

>>> round(12.3456, 2)
12.35

(but +1 for Michael's answer re. the Decimal type.)

If you want a string:

>>> print "%.2f" % 12.34567
12.35



回答3:


From : Python Docs round(x[, n]) Return the floating point value x rounded to n digits after the decimal point. If n is omitted, it defaults to zero. The result is a floating point number. Values are rounded to the closest multiple of 10 to the power minus n; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).

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.

Looks like round (293.466....[, 2]) would do it,




回答4:


I hope this will help.

def do(*args):
    formattedList = [float("{:.2f}".format(num)) for num in args]
    _result =(sum(formattedList))
    result = round(_result,2)
    return result


print(do(23.2332,45.24567,67,54.27))

Result:

189.75



回答5:


x = round(293.4662543, 2)




回答6:


>>> print "%.2f" % 293.44612345
293.45



回答7:


If you need numbers like 2.3k or 12M, this function does the job:

def get_shortened_integer(number_to_shorten):
    """ Takes integer and returns a formatted string """
    trailing_zeros = floor(log10(abs(number_to_shorten)))
    if trailing_zeros < 3:
        # Ignore everything below 1000
        return trailing_zeros
    elif 3 <= trailing_zeros <= 5:
        # Truncate thousands, e.g. 1.3k
        return str(round(number_to_shorten/(10**3), 1)) + 'k'
    elif 6 <= trailing_zeros <= 8:
        # Truncate millions like 3.2M
        return str(round(number_to_shorten/(10**6), 1)) + 'M'
    else:
        raise ValueError('Values larger or equal to a billion not supported')

Results:

>>> get_shortened_integer(2300)
2.3k # <-- str

>>> get_shortened_integer(1300000)
1.3M # <-- str



回答8:


One way:

>>> number = 1
>>> '{:.2f}'.format(number) #1.00
>>> '{:.3f}'.format(number) #1.000

second way:

>>> '%.3f' % number #1.000
>>> '%.3f' % number #1.000

see "format python"



来源:https://stackoverflow.com/questions/3914725/how-to-turn-a-float-number-like-293-4662543-into-293-47-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!