将指数转换为浮点数

发布于 2025-01-03 16:00:22 字数 789 浏览 2 评论 0原文

这是我的代码,尝试将该行的第二个字段从指数转换为浮点数。

outputrrd = processrrd.communicate()
(output, error) = outputrrd
output_lines = output.split('\n')
for line in output_lines:
    m = re.search(r"(.*): ", line)
    if m != None:
        felder = line.split(': ')
        epoch =  felder[0].strip(':')
        utc = epoch2normal(epoch).strip("\n")
        #print felder[1]
        data = float(felder[1])
        float_data = data * 10000000
        print float_data
        resultslist.append( utc + ' ' + hostname + ' ' +  float_data)

但是,程序因以下错误而停止:

File "/opt/omd/scripts/python/livestatus/rrdfetch-convert.py", line 156, in <module>
    data = float(felder[1])
ValueError: invalid literal for float(): 6,0865000000e-01

有人知道原因吗?

This is my code, trying to convert the second field of the line from exponential into float.

outputrrd = processrrd.communicate()
(output, error) = outputrrd
output_lines = output.split('\n')
for line in output_lines:
    m = re.search(r"(.*): ", line)
    if m != None:
        felder = line.split(': ')
        epoch =  felder[0].strip(':')
        utc = epoch2normal(epoch).strip("\n")
        #print felder[1]
        data = float(felder[1])
        float_data = data * 10000000
        print float_data
        resultslist.append( utc + ' ' + hostname + ' ' +  float_data)

But, the program stops with this error:

File "/opt/omd/scripts/python/livestatus/rrdfetch-convert.py", line 156, in <module>
    data = float(felder[1])
ValueError: invalid literal for float(): 6,0865000000e-01

Does anyone know the reason?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

昇り龍 2025-01-10 16:00:23

最简单的方法就是更换!一个简单的例子:

value=str('6,0865000000e-01')
value2=value.replace(',', '.')
float(value2)
0.60865000000000002

The easy way is replace! One simple example:

value=str('6,0865000000e-01')
value2=value.replace(',', '.')
float(value2)
0.60865000000000002
樱花落人离去 2025-01-10 16:00:23

原因是 6,0865000000e-01 中使用了逗号。这不起作用,因为 float() 不支持区域设置。有关详细信息,请参阅 PEP 331

尝试 locale.atof(),或者将逗号替换为点。

The reason is the use of comma in 6,0865000000e-01. This won't work because float() is not locale-aware. See PEP 331 for details.

Try locale.atof(), or replace the comma with a dot.

朮生 2025-01-10 16:00:23

float 值是正确的;您只需根据需要显示它,例如:

print(format(the_float, '.8f'))
# print(f'{the_float:.8f}') # For Python >= 3.6

The float value is correct; you simply need to display it as desired, e.g.:

print(format(the_float, '.8f'))
# print(f'{the_float:.8f}') # For Python >= 3.6
伴我心暖 2025-01-10 16:00:23

这对我有用,试试吧。

def remove_exponent(value):
    decial = value.split('e')
    ret_val = format(((float(decial[0]))*(10**int(decial[1]))), '.8f')
    return ret_val

This work for me, try it out.

def remove_exponent(value):
    decial = value.split('e')
    ret_val = format(((float(decial[0]))*(10**int(decial[1]))), '.8f')
    return ret_val
饮湿 2025-01-10 16:00:23

我认为这对你有用:

def remove_exponent(value):
    """
       >>>(Decimal('5E+3'))
       Decimal('5000.00000000')
    """
    decimal_places = 8
    max_digits = 16

    if isinstance(value, decimal.Decimal):
        context = decimal.getcontext().copy()
        context.prec = max_digits
        return "{0:f}".format(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
    else:
        return "%.*f" % (decimal_places, value)

I think it is useful to you:

def remove_exponent(value):
    """
       >>>(Decimal('5E+3'))
       Decimal('5000.00000000')
    """
    decimal_places = 8
    max_digits = 16

    if isinstance(value, decimal.Decimal):
        context = decimal.getcontext().copy()
        context.prec = max_digits
        return "{0:f}".format(value.quantize(decimal.Decimal(".1") ** decimal_places, context=context))
    else:
        return "%.*f" % (decimal_places, value)
浅浅 2025-01-10 16:00:23

只需将字符串转换为浮点数即可:

new_val = float('9.81E7')

Simply by casting string into float:

new_val = float('9.81E7')
琴流音 2025-01-10 16:00:23

我在尝试从科学/指数表示法中的字符串转换为浮点数时遇到了类似的问题(如果太长,也可能导致指数表示法)

num = '-8e-05'

def scientific_to_float(exponential):
  split_word = 'e'
  e_index = exponential.index('e')
  base = float(exponential[:e_index])
  exponent = float(exponential[e_index + 1:])
  float_number = base * (10 ** exponent)
  return float_number

scientific_to_float(num) # return -8e-05 float number

I had a similar issue trying to convert from string in scientific/exponential notation to a float number (that can result also in exponential notation if too long)

num = '-8e-05'

def scientific_to_float(exponential):
  split_word = 'e'
  e_index = exponential.index('e')
  base = float(exponential[:e_index])
  exponent = float(exponential[e_index + 1:])
  float_number = base * (10 ** exponent)
  return float_number

scientific_to_float(num) # return -8e-05 float number
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文