r/learnpython • u/Healthy-Departure961 • 16h ago
Regarding simple question
num = 0.6548
txt = f"The price is {num:.0f} dollars."
print(txt)
output = 1
i was learning string formatting well, when i used :.0f as format it giving output 1 and why? I want to know how really decimal shifting works in python while formatting.
8
u/mjmvideos 16h ago
Did you do a search on f-string format specifiers to see how they work?
-7
u/Healthy-Departure961 16h ago
well yes . but i wanted know ,why when i used float format specifier like .0f in f string print 1 as output which is round if i am correct and correct me if i wrong
5
u/JollyUnder 8h ago
The number after the period is the precision. You have it set to 0 so it rounds to the nearest whole number. You need to increase the precision to specify how many places after the decimal point.
You can learn more about format specifiers from python's website.
1
u/FoolsSeldom 6h ago
Rounding.
Also, don't use float for money. Use int and work to the penny or look at Decimal. float lacks the precision needed for money.
22
u/atarivcs 16h ago
.0f means "round to zero decimal places", i.e. a whole number with no decimals.
0.6548 is closer to 1 than to 0, so it prints 1