Created
April 6, 2014 18:45
-
-
Save alexer/10009990 to your computer and use it in GitHub Desktop.
get rid of scientific notation of str() for float
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def float2str(val): | |
val, sci, exp = str(val).partition('e') | |
if not sci: | |
return val | |
sign = '' | |
if val[0] in '-': | |
sign = '-' | |
val = val[1:] | |
assert val.count('.') == 1 and val[1] == '.' and val[0] != '0' | |
val = val[0] + val[2:] | |
esign, exp = exp[0], int(exp[1:]) | |
if esign == '-': | |
zeros = exp - 1 | |
val = '0.' + (zeros * '0') + val | |
elif esign == '+': | |
zeros = exp - (len(val) - 1) | |
assert zeros >= 0 | |
val = val + (zeros * '0') + '.0' | |
return sign + val | |
if __name__ == '__main__': | |
assert float2str(0.0000001234567891) == '0.0000001234567891' | |
assert float2str(-0.0000001234567891) == '-0.0000001234567891' | |
assert float2str(12345678492769024.) == '12345678492769024.0' | |
assert float2str(123456784927690241.) == '123456784927690240.0' | |
assert float2str(-12345678492769024.) == '-12345678492769024.0' | |
assert float2str(-123456784927690241.) == '-123456784927690240.0' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to pyrtsa for figuring out that this can be done much easier with:
format(Decimal(str(val)), 'f')