Home > Software design >  Scientific notation not working in python
Scientific notation not working in python

Time:01-10

I am using python version 3.9.5, and trying to use scientific notation using the format method, but it's not working!

I have searched across the web for this, but didn't get anything.

I used the formatting method of format(num, f'.{precision}e') to turn it into scientific notation, and it works for non-decimal numbers, but when I use decimal numbers, it doesn't work:

num = int(10**9) # 1000000000
dec = int(10**-4) # 0.0001

print(format(num, '.5e'))
print(format(dec, '.5e'))

# 1.00000e 09
# 0.00000e 00

As you can see, the second output is meant to be a different result but I got 0.00000e 00


Can somebody please help me solve this, thanks in advance.

CodePudding user response:

int(x) will always be an integer.

print(int(10**-4))

#output 
0

you need to do:

print(format(float(10**-4), '.5e'))

#output
1.00000e-04

CodePudding user response:

In Python 3.9, you can use the f prefix and the {:e} format specifier to format a number in scientific notation. Here's an example:

x = 12345.678
print(f"{x:e}")  # prints 1.234568e 04

If you want to specify the number of decimal places, you can use the .nf syntax, where n is the number of decimal places. For example:

x = 12345.678
print(f"{x:.2e}")  # prints 1.23e 04

Hope this helps.

  • Related