How to suppress scientific notation when printing float values?

后端 未结 12 1263
猫巷女王i
猫巷女王i 2020-11-22 07:12

Here\'s my code:

x = 1.0
y = 100000.0    
print x/y

My quotient displays as 1.00000e-05.

Is there any way to suppress

12条回答
  •  醉话见心
    2020-11-22 07:45

    As of 3.6 (probably works with slightly older 3.x as well), this is my solution:

    import locale
    locale.setlocale(locale.LC_ALL, '')
    
    def number_format(n, dec_precision=4):
        precision = len(str(round(n))) + dec_precision
        return format(float(n), f'.{precision}n')
    

    The purpose of the precision calculation is to ensure we have enough precision to keep out of scientific notation (default precision is still 6).

    The dec_precision argument adds additional precision to use for decimal points. Since this makes use of the n format, no insignificant zeros will be added (unlike f formats). n also will take care of rendering already-round integers without a decimal.

    n does require float input, thus the cast.

提交回复
热议问题