[英]How can i make this float formatting cleaner?
i am given a value eg $50.00.我得到一个价值,例如 50.00 美元。 The output should be 50.0.
输出应为 50.0。 Is there a way to make this cleaner?
有没有办法让这个更干净? Especially my use of double float is bothering me
特别是我对双浮动的使用困扰着我
float(f"{float(d.removeprefix('$')):.1f}")
Assuming you're working with monetary amounts then this might give you more reliable results:假设您使用的是货币金额,那么这可能会给您带来更可靠的结果:
for d in '$50.99', '$50.00', '49.99':
print(float(f"{float(d.removeprefix('$')):.2f}"[:-1]))
Or...或者...
for d in '$50.99', '$50.00', '49.99':
print(int(float(d.removeprefix('$'))*10)/10)
Output:输出:
50.9
50.0
49.9
您可以使用 round 函数将结果限制为小数点后一位。
round(float(d.removeprefix('$')), 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.