4
2

More than 3 years have passed since last update.

Pythonで指数表現のfloatをstrに変換する

Posted at

Pythonでは、数値型を文字列型に変更するためにはstr()でキャストすればよいが、指数表現のfloatをstr()でキャストすると何だかイケてない結果になった。

Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 0.1
>>> str(a)
'0.1'
>>> b = 0.00000000000000000000000000000000000000001
>>> str(b)
'1e-41'

この時、str(b)は
'0.00000000000000000000000000000000000000001'
となってほしい。

以下に記載されている関数を使わせていただくと、うまくできた。

[参考]https://stackoverflow.com/questions/38847690/convert-float-to-string-in-positional-format-without-scientific-notation-and-fa/38983595#38983595

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:
            float_string = '{}{}{}.0'.format(sign, digits, zero_padding)
        else:
            float_string = '{}0.{}{}'.format(sign, zero_padding, digits)
    return float_string
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 0.1
>>> str(a)
'0.1'
>>> b = 0.00000000000000000000000000000000000000001
>>> str(b)
'1e-41'
>>> 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:
...             float_string = '{}{}{}.0'.format(sign, digits, zero_padding)
...         else:
...             float_string = '{}0.{}{}'.format(sign, zero_padding, digits)
...     return float_string
...
>>> float_to_str(b)
'0.00000000000000000000000000000000000000001'
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2