3

To print a floating point number without exponential form, we can write like this:

print('%f' % (10**-8))

But this generally displays zeroes due to precision error. Instead, we can use Decimal.decimal(float) to print a floating point number precisely. But that prints the number in exponential format i.e. 10e-10. And I cannot seem to combine them as I don't know how to format a Decimal like the way I used '%f' to format floats.

So my question is, how to get this thing done the way I want?

Note: The power -8 used here is just an example. The power could be variable. Also, I was wondering if I could print the differences of two numbers with high precision.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36

1 Answers1

3
from decimal import Decimal
print('%.8f' % Decimal(10**-8))

Outputs:

0.00000001

To specify decimal places dynamically you can use this:

from decimal import Decimal

power = 10
print('%.*f' % (power, Decimal(10**-power)))

Prints:

0.0000000001
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • You showed the solution for 10**-8 only. What if the number power is variable? What if it changes? – Meraj al Maksud Jul 15 '18 at 19:07
  • The following code generates error: `>>> from decimal import Decimal >>> a = 10**-8 >>> print("%.*f" % Decimal(a)) Traceback (most recent call last): File "", line 1, in TypeError: * wants int` – Meraj al Maksud Jul 15 '18 at 19:35
  • @MerajAlMaksudMasuk you need to specify two numbers in your format - number of decimal places and the number. – Andrej Kesely Jul 15 '18 at 20:22
  • 3
    Much better to use `.format`-style formatting rather than `%`-based formatting. For `%`-based formatting, a `Decimal` instance is just converted to the nearest `float` first, potentially introducing a rounding error. For `.format`-style formatting, formatting is applied directly to the actual `Decimal` value without a `float` conversion. (Assuming Python >= 3.1.) – Mark Dickinson Aug 28 '18 at 19:05