Python Forum

Full Version: float("{:.2f}" return long number?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello ,
I have a code that divide 2 numbers then give me 2 after the decimal point
in most cased it's working
but something I get this answer :
0.06999999999999999
0.11000000000000001
in most cases I get the correct form:
0.03
0.05
0.01
0.0
what could be the resaon ?
*** I will try to catch the 2 numbers that I'm dividing when this happand

Thanks ,
(Jul-12-2022, 02:34 PM)korenron Wrote: [ -> ]what could be the resaon ?
Floating Point Arithmetic: Issues and Limitations
Basic Answers
It most cases it dos not matter,use f-string to control the amount of digit wanted.
>>> n = 0.06999999999999999
>>> print(f'The number is: {n:.2f}')
The number is: 0.07
>>> print(f'The number is: {n:.3f}')
The number is: 0.070
For eg financial calculation it can matter then use Decimale module
pennies = input('Enter pennies: ')
dollars = Decimal(pennies) * Decimal('.01')
print(f'{pennies} pennies is ${dollars} in dollars')
Output:
Enter pennies: 35 35 pennies is $0.35 in dollars
OK
Thank you,