Handling Floating-Point Numbers with the format() Function
To output real numbers with decimals, use {:f}.
Inside the curly braces, the f format specifier is used to output floating-point (decimal) numbers.
In programming,
floating-pointnumber refers to a real number in which the decimal point can move (or float) within the number.
You can specify the number of decimal places by placing .number after the colon : in the format string.
For example, {:.2f} displays the number with exactly two decimal places.
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 (exponential) notation.
For example, formatting 123.456789 in scientific notation results in 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) # Displays the number without decimal places print(formatted_number) # "123"
Quiz
0 / 1
How would you format float_number to print to 3 decimal places?
float_number = 123.456789formatted_float = "".format(float_number)print(formatted_float)Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result