Last updated: Apr 9, 2024
Reading timeยท2 min
To remove trailing zeros from a decimal:
decimal.to_integral()
method to check if the number has a
fractional part.decimal.normalize()
method to strip any trailing
zeros.from decimal import Decimal num = Decimal('1.230000') def remove_exponent(d): return ( d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize() ) print(remove_exponent(num)) # ๐๏ธ 1.23
The first function is taken from the Decimal FAQ section of the official docs.
The to_integral() method rounds to the nearest integer.
from decimal import Decimal # ๐๏ธ True print(Decimal('1.0000') == Decimal('1.0000').to_integral()) # ๐๏ธ False print(Decimal('1.9000') == Decimal('1.9000').to_integral()) print(Decimal('1.0000').to_integral()) # ๐๏ธ 1
If the number has no decimal part, we use the quantize()
method to round to a
fixed number of decimal places.
If the number has a decimal part, we use the Decimal.normalize() method to strip the rightmost trailing zeros.
from decimal import Decimal print(Decimal('1.230000').normalize()) # ๐๏ธ 1.23 print(Decimal('3.456000000').normalize()) # ๐๏ธ 3.456
We only use the normalize()
method if the number has a decimal part because it
could remove zeros to the left of the decimal.
from decimal import Decimal print(Decimal('500.000').normalize()) # ๐๏ธ 5E+2 print(Decimal('510.100').normalize()) # ๐๏ธ 510.1
Alternatively, you can use the str.rstrip()
method.
This is a two-step process:
str()
class to convert the decimal to a string.str.rstrip()
method to strip the trailing zeros if the number has a
decimal point.from decimal import Decimal num = Decimal('1.230000') string = str(num) without_trailing_zeros = string.rstrip( '0').rstrip('.') if '.' in string else string result = Decimal(without_trailing_zeros) print(result) # ๐๏ธ 1.23
The first step is to convert the decimal to a string.
The str.rstrip() method returns a copy of the string with the provided trailing characters removed.
.
if the decimal part only consisted of trailing zeros.The example also checks whether the string contains a dot, so we don't attempt
to strip trailing zeros from numbers that don't have a decimal part, e.g. 5000
to 5
.
You can learn more about the related topics by checking out the following tutorials: