如何在python中将像293.4662543这样的浮点数变成293.47?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3914725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:19:42  来源:igfitidea点击:

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

pythonnumber-formatting

提问by Shane

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...

如何缩短我得到的浮动结果?我只需要点后的 2 位数字。对不起,我真的不知道如何用英语更好地解释这一点......

Thanks

谢谢

采纳答案by Michael Borgwardt

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

来自浮点指南的Python 备忘单

"%.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 fractionswhich cannotrepresent decimal digits accurately.

使用 round() 是错误的做法,因为浮点数是二进制分数不能准确表示十进制数字。

If you need to do calculations with decimal digits, use the Decimaltype in the decimalmodule.

如果需要使用十进制数字进行计算,请使用模块中的Decimal类型decimal

回答by ghostdog74

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

回答by onaclov2000

From : Python Docsround(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).

来自: Python Docsround(x[, n]) 返回四舍五入到小数点后n位的浮点值x。如果省略 n,则默认为零。结果是一个浮点数。值四舍五入到最接近的 10 的幂减去 n 的倍数;如果两个倍数相等,则从 0 开始舍入(例如,round(0.5) 为 1.0,round(-0.5) 为 -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.

注意 round() 对浮点数的行为可能令人惊讶:例如,round(2.675, 2) 给出 2.67 而不是预期的 2.68。这不是错误:这是大多数十进制分数不能完全表示为浮点数的结果。有关更多信息,请参阅浮点运算:问题和限制。

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

看起来 round (293.466....[, 2]) 会这样做,

回答by Ethan Shepherd

x = round(293.4662543, 2)

x = round(293.4662543, 2)

回答by RichieHindle

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

如果你想要一个数字,使用round()函数:

>>> round(12.3456, 2)
12.35

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

(但迈克尔的回答是+1。Decimal类型。)

If you want a string:

如果你想要一个字符串:

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

回答by chribsen

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

如果您需要2.3k12M 之类的数字,此函数可以完成以下工作:

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

回答by Xavi Martínez

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

回答by AlexNikonov

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"

见“格式化python”