3

I want to print floating point numbers with a set number of significant (i.e. non-zero) digits, but avoid the scientific notation (e).

So, for example, the number 0.000000002343245345 should be printed as 0.000000002343 (and not 2.343e-09)

I know how to define number of significant digits with an e notation:

>>>print('{:.3e}'.format(0.000000002343245345)) 2.343e-09 

And how to print a set number of decimal places without e-notation:

>>>print('{:.12f}'.format(0.000000002343245345)) 0.000000002343 

but not how to combine the two. is there any simple way of doing so?

0

2 Answers 2

4

Here is some code that usually does what you want.

x = 0.000000002343245345 n = 4 from math import log10, floor print('{:.{}f}'.format(x, n - floor(log10(x)) - 1)) 

Note that, due to the lack of exactness in floating-point arithmetic, that this may occasionally give a wrong answer. For example, the floor(log10()) may be one off from what is expected at or very near negative powers of 10 such as 0.1, 0.01, 0.001, and so on. My code seems to work well with those values but that is not guaranteed.

Also, there is no reasonable answer for some combinations of x and n. For example, what do you expect to result from x = 200000 and n = 4? There is no good answer, and my code gives the error

ValueError: Format specifier missing precision 
Sign up to request clarification or add additional context in comments.

1 Comment

The result for x = 200000 and n = 4 is 200000. So is the result for x = 200023 and n = 4. But that's pretty straight forward to implement. Thanks!
2

You have to calculate the number of digits yourself. For four significant digits, this would be

number = 0.000000002343245345 digits = 4 - int(math.ceil(math.log10(number))) print("{:.{}f}".format(number, digits)) # 0.000000002343 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.