How to convert exponential value to string format in python? - python

I'm doing some calculations which give very small decimal numbers for example, 0.0000082
When I'm saving it in a variable, it changes into exponent form. I need the result as a string in the end. So, converting the result using str() is not possible because it keeps the e in the string.
I need the string to have exactly 8 decimal places. Is there any way to do this while keeping the 8 digit precision intact?
Another example: 5.8e-06 should be converted to '0.00000580' The trailing zero in the final string is not important.
I need the string to be used elsewhere. So, this shouldn't be done in the print() function.

The exponential notation is not an inherent property of the number (which is stored as a binary floating point value). It's just the default representation when converting the number to a string with str. You can specify your own formatting options if you convert the number to a string using the format function. Try something like this:
format(5.8e-06, '.8f')
The 8 in the format specifier tells it to use eight digits of precision, while the f requests it to be written as a plain decimal without exponential notation. You can read more about the format notations in the documentation.

Just another idea:
'{0:.7f}'.format(0.0000082)

you can try with :
import decimal
print(str(decimal.Decimal(5.8e-06))[:10])
>>> 0.00000580

print ("{:.6f}".format(1e-4))
will print out
0.000100

You could use print:
>>> number = 1e-08
>>> number
1e-08
>>>print("{:.12f}".format(float(number)))
0.000000010000
or You could convert number and store it in string:
>>> str1 = "{:.12f}".format(float(number))
>>> str1
'0.000000010000'

Related

How to convert a negative exponential number into a decimal number in Python?

I'm having hard time converting the following numbers for example:
-1.9443404027234424e+46
-1.9443404027234425e+36
in a format without the scientific notation (AKA a float like 0.04256 for example).
You can use the :f format specifier:
>>> print("{:.0f}".format(-1.9443404027234424e+46))
-19443404027234423757622069004479676797119627264
Note that the result may not end with 46 zeros because of floating point precision.

Python decimal.Decimal producing result in scientific notation

I'm dividing a very long into much smaller number. Both are of type decimal.Decimal().
The result is coming out in scientific notation. How do I stop this? I need to print the number in full.
>>> decimal.getcontext().prec
50
>>> val
Decimal('1000000000000000000000000')
>>> units
Decimal('1500000000')
>>> units / val
Decimal('1.5E-15')
The precision is kept internally - you just have to explicitly call for the number of decimal places you want at the point you are exporting your decimal value to a string.
So, if you are going a print, or inserting the value in an HTML template, the first step is to use the string format method (or f-strings), to ensure the number is encompassed:
In [29]: print(f"{units/val:.50f}")
0.00000000000000150000000000000000000000000000000000
Unfortunatelly, the string-format minilanguage has no way to eliminate by itself the redundant zeroes on the right hand side. (the left side can be padded with "0", " ", custom characters, whatever one want, but all the precision after the decimal separator is converted to trailing 0s).
Since finding the least significant non-zero digit is complicated - otherwiser we could use a parameter extracted from the number instead of the "50" for precision in the format expression, the simpler thing is to remove those zeros after formatting take place, with the string .rstrip method:
In [30]: print(f"{units/val:.50f}".rstrip("0"))
0.0000000000000015
In short: this seems to be the only way to go: in all interface points, where the number is leaving the core to an output where it is representd as a string, you format it with an excess of precision with the fixed point notation, and strip out the tailing zeros with f-string:
return template.render(number=f"{number:.50f}".rstrip("0"), ...)
Render the decimal into a formatted string with a float type-indicator {:,f}, and it will display just the right number of digits to express the whole number, regardless of whether it is a very large integer or a very large decimal.
>>> val
Decimal('1000000000000000000000000')
>>> units
Decimal('1500000000')
>>> "{:,f}".format(units / val)
'0.0000000000000015'
# very large decimal integer, formatted as float-type string, appears without any decimal places at all when it has none! Nice!
>>> "{:,f}".format(units * val)
'1,500,000,000,000,000,000,000,000,000,000,000'
You don't need to specify the decimal places. It will display only as many as required to express the number, omitting that trail of useless zeros that appear after the final decimal digit when the decimal is shorter than a fixed format width. And you don't get any decimal places if the number has no fraction part.
Very large numbers are therefore accommodated without having to second guess how large they will be. And you don't have to second guess whether they will be have decimal places either.
Any specified thousands separator {:,f} will likewise only have effect if it turns out that the number is a large integer instead of a long decimal.
Proviso
Decimal(), however, has this idea of significant places, by which it will add trailing zeros if it thinks you want them.
The idea is that it intelligently handles situations where you might be dealing with currency digits such as £ 10.15. To use the example from the documentation:
>>> decimal.Decimal('1.30') + decimal.Decimal('1.20')
Decimal('2.50')
It makes no difference if you format the Decimal() - you still get the trailing zero if the Decimal() deems it to be significant:
>>> "{:,f}".format( decimal.Decimal('1.30') + decimal.Decimal('1.20'))
'2.50'
The same thing happens (perhaps for some good reason?) when you treat thousands and fractions together:
>>> decimal.Decimal(2500) * decimal.Decimal('0.001')
Decimal('2.500')
Remove significant trailing zeros with the Decimal().normalize() method:
>>> (2500 * decimal.Decimal('0.001')).normalize()
Decimal('2.5')

How to dynamically format string representation of float number in python?

Hi I would like to dynamically adjust the displayed decimal places of a string representation of a floating point number, but i couldn't find any information on how to do it.
E.g:
precision = 8
n = 7.12345678911
str_n = '{0:.{precision}}'.format(n)
print(str_n) should display -> 7.12345678
But instead i'm getting a "KeyError". What am i missing?
You need to specify where precision in your format string comes from:
precision = 8
n = 7.12345678911
print('{0:.{precision}}'.format(n, precision=precision))
The first time, you specified which argument you'd like to be the number using an index ({0}), so the formatting function knows where to get the argument from, but when you specify a placeholder by some key, you have to explicitly specify that key.
It's a little unusual to mix these two systems, i'd recommend staying with one:
print('{number:.{precision}}'.format(number=n, precision=precision)) # most readable
print('{0:.{1}}'.format(n, precision))
print('{:.{}}'.format(n, precision)) # automatic indexing, least obvious
It is notable that these precision values will include the numbers before the point, so
>>> f"{123.45:.3}"
'1.23e+02'
will give drop drop the decimals and only give the first three digits of the number.
Instead, the f can be supplied to the type of the format (See the documentation) to get fixed-point formatting with precision decimal digits.
print('{number:.{precision}f}'.format(number=n, precision=precision)) # most readable
print('{0:.{1}f}'.format(n, precision))
print('{:.{}f}'.format(n, precision)) # automatic indexing, least obvious
In addition to #Talon, for those interested in f-strings, this also works.
precision = 8
n = 7.12345678911
print(f'{n:.{precision}f}')

Python - Converting String Numbers To Float

I want to convert string numbers on a list to float numbers
and i can't do it, so i need some help.
num = '0.00003533'
print('{:f}'.format(float(num)))
formatting it without decimals, only returns a float of 0.000035, i need the entire string in a float.
print('{:8f}'.format(float(num)))
adding the exact decimal works, but the numbers in the list with decimals varies greatly, so i can't manually add it everytime, how could i automatically add the correct decimal number inside the format?
something like '{':exactdecimalf'} exactdecinal being a variable.
i'm using a module that requires float, which is why i can't print it directly from the string format.
Use this
from decimal import Decimal
num = '0.00003533'
print(Decimal(num)) #0.00003533
if you want to print as string
print ('{:f}'.format(Decimal(num)))
Maybe double precision will suit you.
from decimal import Decimal
print ('{:f}'.format(Decimal(num)))
You can split the string and take the length of the last part with
len(num.split(".")[1])
Then use that as the number of decimals.

Is there a more readable or Pythonic way to format a Decimal to 2 places?

What the heck is going on with the syntax to fix a Decimal to two places?
>>> from decimal import Decimal
>>> num = Decimal('1.0')
>>> num.quantize(Decimal(10) ** -2) # seriously?!
Decimal('1.00')
Is there a better way that doesn't look so esoteric at a glance? 'Quantizing a decimal' sounds like technobabble from an episode of Star Trek!
Use string formatting:
>>> from decimal import Decimal
>>> num = Decimal('1.0')
>>> format(num, '.2f')
'1.00'
The format() function applies string formatting to values. Decimal() objects can be formatted like floating point values.
You can also use this to interpolate the formatted decimal value is a larger string:
>>> 'Value of num: {:.2f}'.format(num)
'Value of num: 1.00'
See the format string syntax documentation.
Unless you know exactly what you are doing, expanding the number of significant digits through quantisation is not the way to go; quantisation is the privy of accountancy packages and normally has the aim to round results to fewer significant digits instead.
Quantize is used to set the number of places that are actually held internally within the value, before it is converted to a string. As Martijn points out this is usually done to reduce the number of digits via rounding, but it works just as well going the other way. By specifying the target as a decimal number rather than a number of places, you can make two values match without knowing specifically how many places are in them.
It looks a little less esoteric if you use a decimal value directly instead of trying to calculate it:
num.quantize(Decimal('0.01'))
You can set up some constants to hide the complexity:
places = [Decimal('0.1') ** n for n in range(16)]
num.quantize(places[2])

Categories

Resources