0

Here's the code:

a = 0.0000224332413
a = str(a)
print(a)  # 2.24332413e-05

How to make exactly str(a) = 0.0000224332413 not 2.24332413e-05 ? Thanks in advance.

  • 3
    Might be worth noting that this has nothing to do with `str`. `0.0000224332413` becomes `2.24332413e-05` long before `str` even knows about it – DeepSpace Jul 25 '20 at 18:41
  • A similar question was asked in: [here](https://stackoverflow.com/questions/38847690/convert-float-to-string-in-positional-format-without-scientific-notation-and-fa). Hope it helps. – ThRnk Jul 25 '20 at 18:41
  • 1
    @DeepSpace I actually don't know what you're referring to there? – roganjosh Jul 25 '20 at 18:44
  • 1
    @roganjosh just pointed out that the "conversion" to scientific notation is not related to `str`, and it happens before it is even called – DeepSpace Jul 25 '20 at 18:47
  • 1
    @DeepSpace that's the part I'm confused about :P The scientific notation is a display, so your comment reads to me like something else is going on. Internally, I'd have thought this was irrelevant – roganjosh Jul 25 '20 at 18:54

2 Answers2

4

You could use f-strings:

a = 0.0000224332413
b = f"{a:.13f}"
print(b)

Returning:

0.0000224332413

Response to the comments: closest thing to dynamically fix the number of decimals might be as follows (requires the number as string to begin with, which defeats the whole purpose):

import decimal

s = '0.0000224332413'
d = decimal.Decimal(s)
n = d.as_tuple().exponent
n *= -1
a = f"{d:.{n}f}"
print(a)

Returning:

0.0000224332413
Gustav Rasmussen
  • 3,720
  • 4
  • 23
  • 53
  • That's a good way. But it's more a hands-on method. Is there any way to insert and count the parameter(13 in this example) automatically ? For instance, some function like this: def function(float): string = str(float) Maybe you know ? – Maksim Yurchak Jul 26 '20 at 07:14
  • The answer has been updated – Gustav Rasmussen Jul 26 '20 at 09:41
0

You can use string literals or string.format(). You can use string literals or string.format().

See this article for more information: https://www.kite.com/python/answers/how-to-suppress-scientific-notation-in-python

a = 0.0000224332413
print(a)  # 2.24332413e-05

b = str(a)
print(b)  # 2.24332413e-05

c = f"{a:.13f}"
print(c)  # 0.0000224332413

d = f"{a:.4f}"
print(d)  # 0.0000

print(f"{a:f}") # 0.000022
Joshua Lowry
  • 1,075
  • 3
  • 11
  • 30
  • My comment above: That's a good way. But it's more a hands-on method. Is there any way to insert and count the parameter(13 in this example) automatically ? For instance, some function like this: def function(float): string = str(float) Maybe you know ? – Maksim Yurchak Jul 26 '20 at 07:17
  • I think Gustav has a good solution. – Joshua Lowry Jul 26 '20 at 14:30