Mavis_Ackerman
Mavis_Ackerman

Reputation: 59

Number of digits after decimal point in scientific (e) format

I want to get desired number of digits after decimal point while keeping answer in scientific format (e.g. 2.989e+10). I know the method format: "{:0.Ae}".format(given_number) where A is number of digits after decimal. However, I'm getting number of digits after the decimal (A) through a variable. Can someone please help me how can I implement it to get the desired result? My code: Consider A as number of digits after decimal point.

for val in [1.049666666666667e-08, 4.248944444444444e+05]:
    val_log = math.log10(val);
    val_e = round(val_log - (0.5 if val_log<0 else 0));
    A = abs(val_e +3);
    valstr = "{:0.Ae}".format(val)
print(valstr)

It is basically number of digits after decimal point(A) = |3 + the value after e|. How should I use value of A in {:0.xe}.format(val) ?

Upvotes: 2

Views: 623

Answers (1)

blhsing
blhsing

Reputation: 106638

You can nest a variable in the precision field, as the documentation of formatted string literals points out in an example with the comment "nested fields".

Below is a more simplified example that limits the precision to 3 digits (or 2 digits after the decimal point):

>>> f = 123.12345
>>> n = 3
>>> print(f'{f:.{n}}')
1.23e+02
>>>

Upvotes: 1

Related Questions