Scientific Numbers in Python: Parse and Format
Python uses e or E for scientific notation; learn to write, parse, format, and safely convert values with float, Decimal, and format specs.
A scientific number in Python is written or parsed with e or E, while its displayed form is controlled separately through formatting. Python calls this scientific notation, and keeping the numeric value, Python type, and resulting string separate prevents most parsing and precision mistakes.
Python scientific notation uses
eorEfor powers of ten,float()orDecimalfor parsing, ande,E,f, orgformat types for display.
What Is a Scientific Number in Python?
Scientific notation writes a number as a coefficient multiplied by a power of ten:
coefficient × 10^exponent
Python replaces the multiplication and power with e or E. For example, 1.25e3 means 1.25 × 10³, which has the value 1250.0. A negative exponent moves the decimal point in the other direction, so 4e-2 has the value 0.04.
Python has no separate “scientific number” type. Scientific notation appears in two different places:
- Numeric syntax:
1.25e3is a floating-point literal in Python source code. - String syntax:
"1.25e3"is text that can be parsed byfloat()orDecimal. - Display formatting:
f"{value:.2e}"creates a string showing an existing value in scientific notation.
Those forms may look similar, but they are different objects. A literal such as 1e3 evaluates to a float. Formatting that float produces a str. Formatting does not rewrite the stored number.
number = 1e3
display = f"{number:.1e}"
print(number)
print(type(number).__name__)
print(display)
print(type(display).__name__)
1000.0
float
1.0e+03
str
A useful mental model is to picture one value wearing different labels. The numeric value is what calculations use. Its type controls how Python stores and operates on it. Formatting chooses the text shown to a person, log file, or report.
Write Scientific Notation as a Python Number
A floating-point literal can use lowercase e or uppercase E. After it, the exponent may have no sign, a plus sign, or a minus sign.
examples = [
1.25e3, # positive exponent
1.25e+3, # explicit positive sign
1.25e-3, # negative exponent
1.25E3, # uppercase E
2e4, # no decimal point required
]
for value in examples:
print(value, type(value).__name__)
1250.0 float
1250.0 float
0.00125 float
1250.0 float
20000.0 float
Even when the mathematical result is a whole number, exponent notation creates a float. 1e3 is equivalent to 1.0e3, so its value is 1000.0, not the integer 1000.
Underscores can make long literals easier to scan when they appear between digits. They do not affect the value.
population_estimate = 1_250_000
measurement = 1_2.5_0e+0_2
print(population_estimate)
print(measurement)
print(type(measurement).__name__)
1250000
1250.0
float
The first value is an int because it has no decimal point or exponent. The second is a float because it uses exponent notation.
This distinction matters when code depends on a type’s behavior. Use type() while experimenting in the Python REPL instead of guessing from how a value happens to print.
Scientific notation does not create a special Python type. An exponent literal creates a float, while formatting creates a string.
Format Numbers With e, E, f, and g
Python’s format specification controls how a number becomes text. Five presentation types cover the usual scientific-notation tasks:
| Format type | Display rule | Meaning of precision |
|---|---|---|
e | Finite values use scientific notation with lowercase e | Digits after the decimal point |
E | Finite values use scientific notation with uppercase E | Digits after the decimal point |
f | Finite values use fixed-point notation | Digits after the decimal point |
g | Chooses fixed or scientific notation | Significant digits |
G | Behaves like g, using uppercase exponent markers | Significant digits |
Here is the same value formatted several ways:
value = 12345.6789
print(f"{value:.2e}")
print(f"{value:.2E}")
print(f"{value:.2f}")
print(f"{value:.4g}")
1.23e+04
1.23E+04
12345.68
1.235e+04
The precision has two meanings here. In .2e and .2f, the 2 requests two digits after the decimal point. In .4g, the 4 requests four significant digits across the whole result.
If precision is omitted for e formatting of a float, Python uses six digits after the decimal point:
print(format(12.0, "e"))
1.200000e+01
You can apply the same format specification through three common interfaces. Each returns a string:
value = 12345.6789
with_f_string = f"{value:.3e}"
with_format = format(value, ".3e")
with_str_format = "{:.3e}".format(value)
print(with_f_string)
print(with_format)
print(with_str_format)
print(type(with_f_string).__name__)
1.235e+04
1.235e+04
1.235e+04
str
Use f when you need an ordinary decimal display instead of exponent notation:
value = 1.25e3
print(f"{value:f}")
print(f"{value:.0f}")
print(f"{value:.2f}")
1250.000000
1250
1250.00
The stored value remains a float in every case. Only the resulting text changes. If this separation between values and representations is still unfamiliar, the staged exercises in the Python learning roadmap provide the surrounding type and string fundamentals.
Parse Scientific Notation From a String
Use float() when external input contains scientific notation and binary floating-point is suitable:
first = float("1.25e3")
second = float("1e-003")
third = float("+1E6")
print(first)
print(second)
print(third)
1250.0
0.001
1000000.0
Calling int() directly on exponent text fails because int() expects an integer string. The characters e3 belong to floating-point syntax, not integer syntax.
try:
int("1e3")
except ValueError:
print("The text is not valid integer syntax.")
The text is not valid integer syntax.
Avoid blindly replacing that call with int(float(text)). int() truncates an existing float toward zero, so a fractional input can be accepted with a changed value. A float may also have rounded a large decimal input before the integer conversion occurs.
This float-based check is approximate: it validates the rounded float, not whether the original text is integral. If fractional source text must never be accepted, use the Decimal-from-original-string approach below instead.
import math
def parse_whole_scientific_float(text):
value = float(text)
if not math.isfinite(value):
raise ValueError("A finite number is required.")
if not value.is_integer():
raise ValueError("A whole number is required.")
return int(value)
print(parse_whole_scientific_float("1.25e3"))
try:
parse_whole_scientific_float("1.25e-1")
except ValueError as error:
print(error)
1250
A whole number is required.
When the input digits must be preserved exactly, validate with Decimal directly from the original string:
from decimal import Decimal
def parse_exact_whole_number(text):
value = Decimal(text)
if not value.is_finite():
raise ValueError("A finite number is required.")
integral = value.to_integral_value()
if value != integral:
raise ValueError("A whole number is required.")
return int(integral)
print(parse_exact_whole_number("1.250e3"))
print(parse_exact_whole_number("100000000000000000001e0"))
1250
100000000000000000001
This version is the safer final pattern for exact whole-number input. It never sends the original decimal digits through a float.
Choose float or Decimal
A float usually stores a binary floating-point approximation. Most decimal fractions cannot be represented exactly as binary fractions, which is why familiar arithmetic can expose extra digits:
print(0.1 + 0.2)
0.30000000000000004
That does not make float unsuitable. It is the normal choice for many measurements, calculations, and APIs where approximate numeric results are expected.
Decimal uses decimal floating-point arithmetic with configurable precision. Construct it from the original string when decimal digits and decimal rounding matter:
from decimal import Decimal
value = Decimal("1.25e3")
total = Decimal("0.1") + Decimal("0.2")
print(format(value, "f"))
print(format(value, ".2e"))
print(total)
1250
1.25e+3
0.3
Do not write Decimal(float(text)) when the purpose is to retain the input exactly. The float conversion may already have introduced a binary approximation. Pass text straight to Decimal.
Use this decision rule:
| Requirement | Better starting choice |
|---|---|
| Ordinary approximate scientific calculations | float |
| Exact decimal input digits | Decimal from the original string |
| Controlled decimal precision and rounding | Decimal |
| Very large decimal exponents beyond a useful float result | Decimal |
| Interoperation with code that already expects floats | float |
| Exact whole-number text in exponent notation | Decimal, validate, then int |
Both types support scientific and fixed-point formatting. The choice between them is about numeric behavior before formatting, not whether either one can display an exponent.
Type and precision mistakes often arrive together. The common Python mistakes guide covers the same habit from a wider angle: check the type at each boundary where text becomes a number or a number becomes text.
Common Scientific-Notation Problems
Use the symptom to find the correct layer. Parsing fixes text input, numeric types fix storage behavior, and formatting fixes display.
| Symptom | Cause | Fix |
|---|---|---|
int("1e3") raises ValueError | Exponent text is not integer syntax | Parse and validate with float or Decimal |
Output uses unwanted e notation | The selected representation uses scientific notation | Format with f, such as f"{value:.2f}" |
| Trailing digits disappear | The value was rounded during conversion or formatting | Use Decimal from the original string and request enough precision |
| A formatted result cannot be used in arithmetic | Formatting returned a string | Keep the numeric value separately from its display string |
int(value) silently loses a fraction | Converting a float truncates toward zero | Check is_integer() before conversion |
A huge integer changes when formatted with e | Integer e formatting first converts the integer to float | Use Decimal(integer) or preserve the exact integer as decimal text |
The huge-integer case is easy to miss. A floating-point presentation type such as e converts an integer to float before formatting it. That conversion can lose low-order digits:
from decimal import Decimal
number = 100000000000000000001
print(format(number, ".20e"))
print(format(Decimal(number), "e"))
print(str(number))
1.00000000000000000000e+20
1.00000000000000000001e+20
100000000000000000001
The first line has lost the final 1. The second and third preserve it.
Formatting can hide or introduce apparent precision changes. Keep the original numeric value, choose its type deliberately, and treat every formatted result as display text.
Where the books fit
For a quick review of literals, types, parsing, and format specifications, Python in One Month builds these pieces in order. Python in Three Months fits readers who need stronger numeric reasoning for projects and interviews. For senior work involving data boundaries, precision policies, and API design, Python for Staff Engineers places these choices inside larger engineering decisions. Keep value, type, and representation separate, and scientific notation becomes predictable.
Frequently asked questions
How do you write a scientific number in Python?
Write a coefficient followed by e or E and a base-10 exponent, such as 1.25e3 or 4E-2. Python treats an exponent literal as a float, so 1e3 produces the float value 1000.0.
How do you convert scientific notation to a number in Python?
Pass the string to float(), as in float('1.25e3'), when binary floating-point is suitable. Use Decimal with the original string when decimal digits must remain exact or the exponent may exceed the practical range of a float.
Why does int('1e3') raise ValueError?
int() parses strings written with integer syntax, and 1e3 uses floating-point exponent syntax. Parse and validate the value first, then convert it only after confirming that it is finite and has no fractional part.
How do you stop Python from displaying scientific notation?
Format the value with the f presentation type, such as f'{value:.2f}'. Formatting returns a string with fixed-point notation; it does not change the stored numeric value or its Python type.
What is the difference between e, f, and g formatting?
For finite values, the e type always uses scientific notation, while f always uses fixed-point notation. NaN and infinity retain their special textual forms. With e and f, precision counts digits after the decimal point; with g, precision counts significant digits and Python selects fixed or scientific notation according to magnitude.