Handling Floating-Point Numbers with the format() Function
To output real numbers with decimals, use {:f}
.
The f
Inside the curly braces, a format specifier is used to output floating-point (decimal) numbers.
In programming,
floating-point
number refers to a real number in which the decimal point can move (or float) within the number.
By using .number
to the right of the colon :
, you can specify the number of decimal places.
For example, {:.2f}
will only display two decimal places of the given real number.
float_number = 123.4567 formatted_float = "float_number: {:.2f}".format(float_number) print(formatted_float) # "float_number: 123.46"
Outputting in Scientific Notation
Use {:e}
to display floating-point numbers in scientific notation using exponents.
For example, displaying 123.456789
in scientific notation would give 1.23e+02
.
float_number = 123.456789 scientific_formatted = "{:.2e}".format(float_number) print(scientific_formatted) # "1.23e+02"
Removing Decimal Places
To remove the decimal places from a floating-point number, use :.0f
.
number = 123.0 formatted_number = "{:.0f}".format(number) # No decimal places displayed print(formatted_number) # "123"
How would you format float_number
to print to 3 decimal places?
float_number = 123.456789
formatted_float = "
".format(float_number)
print(formatted_float)
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result