首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么小数点被忽略?

为什么小数点被忽略?
EN

Stack Overflow用户
提问于 2020-02-11 04:31:15
回答 2查看 54关注 0票数 0

所以我正在做这个小的复利计算器,我有一个问题,我不知道怎么解决!出于某种原因,python似乎并不关心数字中有小数这一事实。例如,如果一个数字在代码中是12588.01,那么它将被视为12588。任何帮助都是非常感谢的!

代码语言:javascript
复制
p = 12588.01  #principle
r = 4.9  #rate as percent
t = 20  #time

# math
r = r / 100

# math and output
for i in range(t):
    interest = p * r
    #interest = round(interest, 2)

    #generates the spaces between the time and numbers
    timeSpace = 5 - len(str(i+1))
    timeSpace = " " * int(timeSpace)

    #generates the spaces used in the first part of the output
    firstSpace = 10 - len(str(round(p)))
    firstSpace = " " * int(firstSpace)

    #generated the space used in the second part of the output
    secondSpace = 10 - len(str(round(interest)))
    secondSpace = " " * int(secondSpace)

    #output

    #print("Year: %d%s|%d%s|%d%s|%d" % (i+1, timeSpace, round(p, 2), firstSpace, interest, secondSpace, round(interest+p, 2)))
    print("Year: %d%s|%d%s|%d%s|%d" % (i+1, timeSpace, float(p), firstSpace, float(interest), secondSpace, float(interest+p)))

    p = p + interest
    #p = round(p, 2)

这个计算器正在使用货币,因此应该循环,但是在我尝试修复代码的过程中,我将它们注释掉了。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-02-11 04:33:18

您使用%d打印浮点数,这是用于整数的。使用%.2f将浮点数打印到小数点后两位。

票数 0
EN

Stack Overflow用户

发布于 2020-02-11 04:51:34

使用具有正确格式的字符串格式:

代码语言:javascript
复制
p = 12588.01  #principle
r = 4.9  #rate as percent
t = 20  #time

r /= 100

for i in range(t):
    interest = p * r
    print(f"Year: {i+1:<5d}|{p:<10.2f}|{interest:<10.2f}|{interest+p:.2f}")
    p += interest
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60157955

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档