0
votes

I've read through the Decimal documentation and researched other methods around suppressing scientific notation expression in Python, but I am having an issue with the Decimal package not working as I expect, and I cannot figure out how to get my desired output.

I have a string - my_tick = "0.0000005"

type(my_tick)
<class 'str'>

When I pass this into Decimal(), the object is formatted and returned in scientific notation:

from decimal import *

formatted_tick = Decimal(my_tick)
print(formatted_tick)
5E-7

If I call getcontext() I see that my default precision is set to 28 decimal places:

getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[InvalidOperation, FloatOperation], traps=[InvalidOperation, DivisionByZero, Overflow])

I have tried to wrap the string as a float, but it still returns in scientific notation:

formatted_tick = Decimal(repr(float(my_tick)))
print(formatted_tick)
5E-7

Both result in a Decimal object with a value of 5E-7

For my function, it must remain a decimal object with a value of 0.0000005, as far as formatting, I may have this same issue with other numbers, and I do not necessarily know the precision ahead of time so a native solution that can handle precision of 1 to 10 decimal places on it's own is needed. Does anyone know why Decimal is using scientific notation when the precision is set to 28?

Thank you ahead of time,

1
You need to be careful to distinguish between Decimal objects and string representations of those objects. A Decimal object isn't related to any particular representation: Decimal("1e-7") and Decimal("0.0000001") give the exact same object. In this question, you're asking for a specific representation of your Decimal object, and that's the domain of string formatting, as in @MatthewStory's answer. - Mark Dickinson

1 Answers

1
votes

The str.format will format your number the way you want if you specify that it should be outputted as a float with :f like this:

>>> "{:f}".format(decimal.Decimal("0.0000000005"))
"0.0000000005"

If you wanted this behavior to be the default string representation behavior for your decimal you could define a class like this:

 class NoScientificNotation(decimal.Decimal):
     def __str__(self):
         return "{:f}".format(self)

And then use it like a `Decimal:

>>> NoScientificNotation("0.0000000005")
Decimal('0.0000000005')

Without issue.