Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Python Decimal object to a specified precision

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!

like image 831
Joshua Burns Avatar asked Feb 25 '13 20:02

Joshua Burns


People also ask

How do you set decimal precision in Python?

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.

How do you format decimals in Python?

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.

What is .2f in Python?

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 .


1 Answers

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.

like image 198
Martijn Pieters Avatar answered Sep 19 '22 05:09

Martijn Pieters