# others - python 将浮点数转换为不带科学符号和错误精度的字符串

```
```
>>> n = 0.000000054321654321

>>> n

5.4321654321e-08 # scientific notation

``````

```
```
>>> str(n)

'5.4321654321e-08'

``````

```
```
>>> format(0.00000005, '.20f')

'0.00000005000000000000'

``````

```
```
>>> format(0.1, '.20f')

'0.10000000000000000555'

``````

```
```
>>> format(4.5678e-20, '.20f')

'0.00000000000000000005'

``````

```
```
>>> format(0.0000000005, 'f')

'0.000000'

``````

• 首先使用`str()``repr()`将float转换为字符串
• 然后，从该字符串创建一个新的 `Decimal`实例，
• `Decimal.__format__`支持提供所需结果的`f`标志，与`float` s不同，它打印实际精度而不是默认精度，

```
```
import decimal

# create a new context for this task

ctx = decimal.Context()

# 20 digits should be enough for everyone :D

ctx.prec = 20

def float_to_str(f):

" ""

Convert the given float to a string,

without resorting to scientific notation

" ""

d1 = ctx.create_decimal(repr(f))

return format(d1, 'f')

``````

```
```
>>> float_to_str(0.1)

'0.1'

>>> float_to_str(0.00000005)

'0.00000005'

>>> float_to_str(420000000000000000.0)

'420000000000000000'

>>> float_to_str(0.000000000123123123123123123123)

'0.00000000012312312312312313'

``````

```
```
def float_to_str(f):

float_string = repr(f)

if 'e' in float_string: # detect scientific notation

digits, exp = float_string.split('e')

digits = digits.replace('.', '').replace('-', '')

exp = int(exp)

zero_padding = '0' * (abs(int(exp)) - 1) # minus 1 for decimal point in the sci notation

sign = '-' if f <0 else ''

if exp> 0:

else:

return float_string

n = 0.000000054321654321

assert(float_to_str(n) == '0.000000054321654321')

n = 0.00000005

assert(float_to_str(n) == '0.00000005')

n = 420000000000000000.0

assert(float_to_str(n) == '420000000000000000.0')

n = 4.5678e-5

assert(float_to_str(n) == '0.000045678')

n = 1.1

assert(float_to_str(n) == '1.1')

n = -4.5678e-5

assert(float_to_str(n) == '-0.000045678')

``````

• python 2：使用`ctx.create_decimal()`: `2.43655490875`

• python 2：使用字符串操作： `0.305557966232`

• python 3：使用`ctx.create_decimal()`: `0.19519368198234588`

• python 3：使用字符串操作： `0.2661344590014778`

```
```
from timeit import timeit

CODE_TO_TIME = '''

float_to_str(0.000000054321654321)

float_to_str(0.00000005)

float_to_str(420000000000000000.0)

float_to_str(4.5678e-5)

float_to_str(1.1)

float_to_str(-0.000045678)

'''

SETUP_1 = '''

import decimal

# create a new context for this task

ctx = decimal.Context()

# 20 digits should be enough for everyone :D

ctx.prec = 20

def float_to_str(f):

" ""

Convert the given float to a string,

without resorting to scientific notation

" ""

d1 = ctx.create_decimal(repr(f))

return format(d1, 'f')

'''

SETUP_2 = '''

def float_to_str(f):

float_string = repr(f)

if 'e' in float_string: # detect scientific notation

digits, exp = float_string.split('e')

digits = digits.replace('.', '').replace('-', '')

exp = int(exp)

zero_padding = '0' * (abs(int(exp)) - 1) # minus 1 for decimal point in the sci notation

sign = '-' if f <0 else ''

if exp> 0:

else:

return float_string

'''

print(timeit(CODE_TO_TIME, setup=SETUP_1, number=10000))

print(timeit(CODE_TO_TIME, setup=SETUP_2, number=10000))

``````

```
```
import decimal

def float_to_string(number, precision=20):

return '{0:.{prec}f}'.format(

decimal.Context(prec=100).create_decimal(str(number)),

prec=precision,

).rstrip('0').rstrip('.') or '0'

``````

```
```
>> float_to_string(0.10101010101010101010101010101)

'0.10101010101'

``````

```
```
import decimal

def float_to_string(number, precision=20):

return '{0:.{prec}f}'.format(

number, prec=precision,

).rstrip('0').rstrip('.') or '0'

``````

```
```
>> float_to_string(0.1, precision=10)

'0.1'

>> float_to_string(0.1)

'0.10000000000000000555'

>>float_to_string(0.1, precision=40)

'0.1000000000000000055511151231257827021182'

>>float_to_string(4.5678e-5)

'0.000045678'

>>float_to_string(4.5678e-5, precision=1)

'0'

``````

```
```
>> float_to_string(0.1, precision=10000)

'0.1000000000000000055511151231257827021181583404541015625'

``````

```
```
>> float_to_string(100)

'100'

``````

```
```
import decimal

import math

ctx = decimal.Context()

def f1(number, prec=20):

ctx.prec = prec

return format(ctx.create_decimal(str(number)), 'f')

def f2(number, prec=20):

return '{0:.{prec}f}'.format(

number, prec=prec,

).rstrip('0').rstrip('.')

k = 2*8

for i in range(-2**8,2**8):

if i<0:

value = -k*math.sqrt(math.sqrt(-i))

else:

value = k*math.sqrt(math.sqrt(i))

value_s = '{0:.{prec}E}'.format(value, prec=10)

n = 10

print ' | '.join([str(value), value_s])

for f in [f1, f2]:

test = [f(value, prec=p) for p in range(n)]

print 't{0}'.format(test)

``````

• 对于反斜杠，将看到类似'-000'或000'的字符串'，

```
```
a=5.4321654321e-08

'{0:.40f}'.format(a).rstrip(" 0" ) # float number and delete the zeros on the right

# '0.0000000543216543210000004442039220863003' # there's roundoff error though

``````