简体   繁体   中英

how to convert integer to exponential in different forms for the same value in python

I am trying to get exponential value in different form for the same value. for example:

print('{:e}'.format(100))

ans=1.000000e+02. this is working fine

I want answer like,

ans1: 0.10000e+03

ans2: 0.01000e+04

ans3: 10000.00000e-2

how to achieve these?

I hardcoded a formatter that would satisfy your need. The code can be improved for better efficiency and readability but I will leave that to you.
I am assuming the build-in format function is decimals_power_of_ten=0 , you can see in the examples and changed as you need. Here's the code:

def custom_format(num, decimals_power_of_ten, digits_after_dot):
    formated = '{:e}'.format(num)
    parts = formated.split('e')
    new_decimal = ''
    new_power = ''

    if decimals_power_of_ten != 0:
        part1 = float(parts[0])*(10**decimals_power_of_ten)
        d = "{:." +str(digits_after_dot)+ "f}"
        new_decimal = d.format(part1)
       
        new_power_int = int(parts[1][1:]) - decimals_power_of_ten

        if new_power_int > 0 and new_power_int < 9:
            new_power =  'e+0' + str(new_power_int)
        else:
            if new_power_int > 0:
                new_power = 'e+'+str(new_power_int)
            else:
                new_power = 'e'+str(new_power_int)
        formated = new_decimal + new_power
    
    return formated

Your examples and corresponding outputs:

print(custom_format(100, 0, 5))
print(custom_format(100, -1, 5))
print(custom_format(100, -2, 5))
print(custom_format(100, 4, 5))

1.000000e+02
0.10000e+03
0.01000e+04
10000.00000e-2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM