花车有问题吗?(可能非常简单)

2024-10-01 17:32:27 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我试着把一个浮点数四舍五入到小数点后两位,如果有更多的浮点数,它可以正常工作,但如果没有,则会中断

不管怎样,这就是我所拥有的:

    income=input("Enter your expected annual income in USD.")
    if floatcheck(income) == True:
        Income=float(income)
        income=str(round(Income, 2))

所以我试图:总是让它保持两位小数(如果有更多的小数,这很好,但是如果它是一个整数,它实际上会加上一个.0,这在货币上看起来很奇怪),或者让整数根本没有小数。我尝试了很多不同的方法,比如把它四舍五入到3,希望再加上0,再加上+0.00 哦,我已经将上面的floatcheck定义为:

def floatcheck(str):
    try:
        float(str)
        return True
    except ValueError:
        return False

无论如何,我认为这是超级容易解决的问题,但我似乎无法在任何地方找到答案


Tags: trueinputyourreturn整数floatexpectedenter
3条回答

想要格式化的数字,请查看format specifiers的解释

>>> num = 2
>>> f"{num:.2f}"
'2.00'
>>> num = 2.3455
>>> f"{num:.2f}"
'2.35'

以以下为例:

print(round(2.665, 2))
print(round(2.675, 2))

Output

2.67
2.67

注意:浮动round()的行为可能令人惊讶。注意round(2.675, 2)给出了2.67,而不是预期的2.68。这不是一个错误:这是因为大多数小数不能精确地表示为浮点

当十进制数2.675转换为二进制浮点数时,它再次被二进制近似值替换,其精确值为:

2.67499999999999982236431605997495353221893310546875

因此,它被四舍五入到2.67

如果你需要一个精确的情况,考虑使用浮点运算的十进制模块:

from decimal import Decimal

# normal float
income= 2.675
print(round(income, 2))

# using decimal.Decimal (passed float as string for precision)
income= Decimal('2.675')
print(round(income, 2))


Output

2.67
2.68

尝试使用十进制和四舍五入,如下所示。我添加了float来查看它与十进制函数的比较

    from decimal import *
    n = ['20','20.25','45','35','56.43','20.25','20.00','78.906']
    for i in n:
        print(round(float(i),2),'......',round(Decimal(i),2))

输出:

20.0 ...... 20.00
20.25 ...... 20.25
45.0 ...... 45.00
35.0 ...... 35.00
56.43 ...... 56.43
20.25 ...... 20.25
20.0 ...... 20.00
78.91 ...... 78.91

相关问题 更多 >

    热门问题