Handling Floating-Point Numbers with the format() Function
To output real numbers with decimals, use {:f}
.
The f
inside the curly braces is a format specifier used for outputting floating-point (floating decimal point) numbers.
In programming,
floating-point
refers to a real number where the decimal point can float.
By using .number
to the right of :
, you can specify the number of decimal places.
For example, {:.2f}
will only display two decimal places of the given real number.
Floating point formatting example
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
.
Scientific notation example
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
.
Removing insignificant decimals
number = 123.0 formatted_number = "{:.0f}".format(number) # No decimal places displayed print(formatted_number) # "123"
Mission
0 / 1
How would you format float_number
to print to 3 decimal places?
float_number = 123.456789
formatted_float = "
".format(float_number)
print(formatted_float)
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result