How to suppress scientific notation when printing float values?

后端 未结 12 1392
猫巷女王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:46

    This is using Captain Cucumber's answer, but with 2 additions.

    1) allowing the function to get non scientific notation numbers and just return them as is (so you can throw a lot of input that some of the numbers are 0.00003123 vs 3.123e-05 and still have function work.

    2) added support for negative numbers. (in original function, a negative number would end up like 0.0000-108904 from -1.08904e-05)

    def getExpandedScientificNotation(flt):
        was_neg = False
        if not ("e" in flt):
            return flt
        if flt.startswith('-'):
            flt = flt[1:]
            was_neg = True 
        str_vals = str(flt).split('e')
        coef = float(str_vals[0])
        exp = int(str_vals[1])
        return_val = ''
        if int(exp) > 0:
            return_val += str(coef).replace('.', '')
            return_val += ''.join(['0' for _ in range(0, abs(exp - len(str(coef).split('.')[1])))])
        elif int(exp) < 0:
            return_val += '0.'
            return_val += ''.join(['0' for _ in range(0, abs(exp) - 1)])
            return_val += str(coef).replace('.', '')
        if was_neg:
            return_val='-'+return_val
        return return_val
    

提交回复
热议问题