Convert Scientific Notation to Float

后端 未结 3 2180
太阳男子
太阳男子 2020-12-09 14:44

Encountered a problem whereby my JSON data gets printed as a scientific notation instead of a float.

import urllib2
import json
import sys

url = \'https://b         


        
3条回答
  •  孤城傲影
    2020-12-09 15:29

    There are some approaches:


    #1 float(...) + optionally round() or .format()

    x = float(1.357e-05)
    round(x, 6)
    "{:.8f}".format(x)
    

    #2 with decimal class

    import decimal
    
    tmp = decimal.Decimal('1.357e-05')
    print('[0]', tmp)
    # [0] 0.00001357
    
    tmp = decimal.Decimal(1.357e-05)
    print('[1]', tmp)
    # [1] 0.0000135700000000000005188384444299032338676624931395053863525390625
    
    decimal.getcontext().prec = 6
    tmp = decimal.getcontext().create_decimal(1.357e-05)
    print('[2]', tmp)
    # [2] 0.0000135700
    

    #3 with .rstrip(...)

    x = ("%.17f" % n).rstrip('0').rstrip('.')
    

    Note: there are counterparts to %f:
    %f shows standard notation
    %e shows scientific notation
    %g shows default (scientific if 5 or more zeroes)

提交回复
热议问题