Formatting Float Output in Python: Scientific Notation and Fixed‑Point Representations
This tutorial demonstrates how Python automatically displays large float values in scientific notation and shows how to use the % operator and the format() method to produce either nicely formatted scientific notation or full‑precision decimal output for float numbers.
Note: All numeric values in the examples are fabricated for illustration only; the author is a Python beginner writing a tutorial for personal reference and welcomes corrections.
When a float has many digits, Python prints it in exponential (scientific) form by default. The following code calculates the mass of the Earth based on a user‑provided diameter and shows the default exponential output.
import math
m = 5.52 # density
r = float(input('请输入地球直径(km):'))
V = 4*math.pi*r**3/3
W = m*V*1000**3
print('地球重量为', W, '吨')
#运行结果
请输入地球直径(km):1234
地球重量为 4.344833777941348e+19 吨The raw exponential output is often undesirable because it contains many decimal places. You can format the output to a cleaner scientific notation using either the % formatting operator or the str.format() method.
import math
m = 5.52
r = float(input('请输入地球直径(km):'))
V = 4*math.pi*r**3/3
W = m*V*1000**3
print('地球重量为%.2e吨' % W) # .2 limits to two decimal places
print('地球重量为{:.2e}吨'.format(W))Both approaches produce identical results, e.g., "地球重量为4.34e+19吨".
If you need the full integer value instead of scientific notation, replace the format specifier with f (or %.f ) to output a fixed‑point representation.
import math
m = 5.52
r = float(input('请输入地球直径(km):'))
V = 4*math.pi*r**3/3
W = m*V*1000**3
print('地球重量为%.f吨' % W)In summary, by changing the format specifier you can switch between exponential (e) and fixed‑point (f) output: e yields scientific notation, while f yields the complete decimal value.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.