I've spent countless hours researching, reading, testing, and ultimately confused and dismayed at Python's Decimal object's lack of the most fundamental concept: Formatting a Decimal's output to a string.
Let's assume we have some strings or Decimal objects with the following values:
0.0008
11.1111
222.2222
3333.3333
1234.5678
The goal is to simply set the Decimal's precision to the second decimal place. Eg, 11.1111
would be formatted as 11.11
, and 1234.5678
as 1234.57
.
I envision code similar to the following:
import decimal
decimals = [
decimal.Decimal('0.0008'),
decimal.Decimal('11.1111'),
decimal.Decimal('222.2222'),
decimal.Decimal('3333.3333'),
decimal.Decimal('1234.5678'),
]
for dec in decimals:
print dec.as_string(precision=2, rounding=ROUND_HALF_UP)
The resulting output would be:
0.00
11.11
222.22
3333.33
1234.57
Obviously we cannot make use of the Decimal's context's precision, because this takes into consideration the TOTAL number of digits, not just decimal precision.
I'm also not interested in converting the Decimal to a float to output its value. The ENTIRE reason behind Decimal is to avoid storing and running calculations on floats.
What other solutions are there? I understand there are many other similar questions on stack overflow, but none of them have I found to resolve the underlying issue I am inquiring of.
Thanks much!
Using “%”:- “%” operator is used to format as well as set precision in python. This is similar to “printf” statement in C programming. Using format():- This is yet another way to format the string for setting precision.
To format decimals, we will use str. format(number) where a string is '{0:. 3g}' and it will format string with a number. Also, it will display the number with 1 number before the decimal and up to 2 numbers after the decimal.
2f is a placeholder for floating point number. So %d is replaced by the first value of the tuple i.e 12 and %. 2f is replaced by second value i.e 150.87612 .
Just use string formatting or the format()
function:
>>> for dec in decimals:
... print format(dec, '7.2f')
...
0.00
11.11
222.22
3333.33
1234.57
decimal.Decimal
supports the same format specifications as floats do, so you can use exponent, fixed point, general, number or percentage formatting as needed.
This is the official and pythonic method of formatting decimals; the Decimal
class implements the .__format__()
method to handle such formatting efficiently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With