Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I condition the format specifier on the value of the argument?

I would like to output the values as {:f} if they are above 0.001, say, otherwise as {:e} (exponentials).

I wonder if I can do this within one string formatting line, that is not conditioning on the line that actually prints, but inside it. Are lambda expressions permitted? (Side note: where are they permitted, really?)

FTR, this is my output string:

print("{:f}".format(my_float))
like image 840
user1603472 Avatar asked Dec 02 '25 15:12

user1603472


2 Answers

I think I'd use "{:g}". This will flop back and forth between exponential notation and normal float notation depending on the value:

>>> '{:g}'.format(0.001)
'0.001'
>>> '{:g}'.format(0.0000001)
'1e-07'

In contrast to "{:e}" which is always exponential...

>>> '{:e}'.format(0.001)
'1.000000e-03'
like image 160
mgilson Avatar answered Dec 05 '25 05:12

mgilson


Adding the condition into the format is one way I could think

>>> x = 0.0001276
>>> '{:{type}}'.format(x, type='f' if x>0.001 else 'e')
'1.276000e-04'
>>> x = 0.01
>>> '{:{type}}'.format(x, type='f' if x>0.001 else 'e')
'0.010000'

This is better than lambda, in my opinion.

To do away with if else, you can go with and or operation

(x>0.01 and 'f') or 'e'
like image 44
thiruvenkadam Avatar answered Dec 05 '25 04:12

thiruvenkadam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!