Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of digits in exponent

Is it possible to set the number of digits to be used for printing the exponent of a floating-point number? I want to set it to 3.

Currently,

f = 0.0000870927939438012
>>> "%.14e"%f
'8.70927939438012e-05'
>>> "%0.14e"%f
'8.709279e-005'

What I want to print is: '8.70927939438012e-005'

like image 276
nmadzharov Avatar asked Mar 28 '12 15:03

nmadzharov


People also ask

How do you find the number of digits?

The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

How many digits are there in 2 to the power 100?

2100 begins in a 2 and is 31 digits long.

How many digits are there in 2 to the power 30?

So the log of 230 is about 9.03, telling you that there are ten digits.


2 Answers

There is a no way to control that, best way is to write a function for this e.g.

def eformat(f, prec, exp_digits):     s = "%.*e"%(prec, f)     mantissa, exp = s.split('e')     # add 1 to digits as 1 is taken by sign +/-     return "%se%+0*d"%(mantissa, exp_digits+1, int(exp))  print eformat(0.0000870927939438012, 14, 3) print eformat(1.0000870927939438012e5, 14, 3) print eformat(1.1e123, 4, 4) print eformat(1.1e-123, 4, 4) 

Output:

8.70927939438012e-005 1.00008709279394e+005 1.1000e+0123 1.1000e-0123 
like image 93
Anurag Uniyal Avatar answered Sep 29 '22 08:09

Anurag Uniyal


You can use np.format_float_scientific

from numpy import format_float_scientific  f = 0.0000870927939438012  format_float_scientific(f, exp_digits=3) # prints '8.70927939438012e-005'  format_float_scientific(f, exp_digits=5, precision=2) #prints '8.71e-00005' 
like image 44
Khalil Al Hooti Avatar answered Sep 29 '22 10:09

Khalil Al Hooti