2

I have not found an answer for this...

Suppose I have the following rational numbers: 0.00000857 and 1.03.

Using %f rounds to 6 digits so 0.00000857 becomes 0.000009. Also 1.03 would be padded to 1.030000. Setting .8f would print 0.00000857 as 0.00000857, but 1.03 would be padded. %g returns exponential notation and I do not want it.

How can I print (stringify) the two numbers as they are, i.e. 0.00000857 and 1.03?

alain
  • 165
  • 8
  • Maybe this answer can help you: https://stackoverflow.com/questions/65972737/how-to-format-median-and-errors-differently-in-corner-plots/65976170?noredirect=1#comment116654449_65976170 – Carlos Melus Feb 10 '21 at 19:23
  • 1
    There's probably a better way, but this works `"{0:.8f}".format(x).rstrip('0')` – 001 Feb 10 '21 at 19:28
  • What do you mean by "as they are"? Are you familiar with how computers treat floating-point numbers? If not, please look it up – Pythonista anonymous Feb 10 '21 at 22:30

1 Answers1

1

You could just round the float to desired decimal places(6 in your case) and subsequently formate it to such.

print('{:.6f}'.format(0.00000857))

to remove the undesirable trailing zeros:

print('{:.6f}'.format(1.03).rstrip('0').rstrip('.'))
geobudex
  • 536
  • 1
  • 8
  • 24