简体   繁体   中英

How can i make this float formatting cleaner?

i am given a value eg $50.00. The output should be 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM