简体   繁体   中英

Generating float numbers from integer decimal index in Python

Given I have any given index integer how can I generate float numbers or strings which references the decimal point as 0

Examples:

Given an increment factor digit 1:
n=-4 ~ "0.0001"
n=-10 ~ "0.0000000001"
Given an increment factor digit 2:
n=1 ~ "2.0"
n=5 ~ "20000.0"
n=-5 ~ "0.00002"

Just use scientific notation:

n = 1e-4  # 0.0001
n = 1e-10 # 0.0000000001
n = 2e1   # 2.0
n = 2e5   # 20000.0
n = 2e-5  # 0.00005

This is built into python. Doing something like

x = 5.3e6

is equivalent to doing

x = 5.3 * (10 ** 6)

It is worth noting that while the number before e may be a float itself, the number after e (the power of 10) must be an integer. Also note that this returns floating point numbers always so if you wanted it as a string for some reason you would have to call str() on the result.

Seems like you just need a power of ten in there. So take the digit, d , and multiply it by 10^n . When doing this however you should take note that the positive numbers are one factor of 10 off since it starts at 0, not 1. To fix that just subtract one from n if it's positive. This lambda does the trick: lambda n: n-1 if (n>0) else n

# When the factor (d) is 1
n=2      f = d*10^n     "100.0"
n=-1     f = d*10^n     "0.1"

# When the factor (d) is 2
n = 4    f = d*10^n     "20000.0"
n = -5   f = d*10^n     "0.00002"

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