【问题标题】:How to convert float to be represented as XE-Y for any float如何将浮点数转换为任何浮点数的 XE-Y
【发布时间】:2019-05-04 13:53:53
【问题描述】:

我正在解析一个文件,其中包含由空格分隔的浮点数行,格式为: +/-0.XXXE-8 读取浮点数并将它们保存在列表中,它会更改为 +/-X.XXXE-9。

我正在尝试将数字打印为 +/-0.XXXE-8(我读到的格式相同)但没有运气。

输入文件中的示例行是:

0.43578E-08  0.48992E-08  0.54452E-08  0.59816E-08  0.64918E-08  0.69577E-08

读取后打印该行的输出:

4.357800e-09 4.899200e-09 5.445200e-09 5.981600e-09 6.491800e-09 6.957700e-09

有没有办法将任何浮点数转换为0.XXXE-8,无论数字是多少,例如:

x = 1.3E-9
print(func(x)) -> 0.13E-8

希望能得到一些帮助

谢谢

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 您应该编辑问题以显示您到目前为止所做的尝试。
  • 你的代码可能有错误?
  • 我尝试搜索对话方法但没有找到,我认为我在解析代码中没有错误,因为数字相同,唯一的区别是它们在解析后保留的方式
  • @PatrickArtner 是的,我愿意,但是因为格式很重要,因为它会被输入到其他程序(不是我写的)我需要将其更改为以 0 而不是 1 开头跨度>

标签: python-3.x printing floating-point


【解决方案1】:

你已经意识到这些数字在数字上是相同的。

所以这只是一个显示问题,您可以通过自己格式化来避免:

data = [0.43578E-08, 0.48992E-08, 0.54452E-08, 0.59816E-08, 0.64918E-08, 0.69577E-08]

def format_float_weirdly(myfloat):
    """Formats a float to 0.xxxxxxxe-08 if it would be presened as x.xxxxxxe-09
    when normally formatted. If not, the normal format is outputted.""" 
    float_String = f"{myfloat:.8n}"
    if float_String[1] == "." and float_String.endswith("e-09"):
        float_String = "0." + float_String.replace(".","").replace("e-09","e-08")
    return float_String


d2 = [format_float_weirdly(f) for f in data]
print(data)
print(d2)

输出:

# printout of data
[4.3578e-09, 4.8992e-09, 5.4452e-09, 5.9816e-09, 6.4918e-09, 6.9577e-09]

['0.43578e-08', '0.48992e-08', '0.54452e-08', '0.59816e-08', '0.64918e-08', '0.69577e-08']

您可以通过对“普通字符串表示”进行一些数学运算和字符串切片来调整它以适应“任何”其他表示。 Afaik 没有内置的方法可以通过normal string formatting 手段“格式化”你想要的浮点数。

【讨论】:

  • 谢谢,正是我需要的!也将不胜感激
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-25
相关资源
最近更新 更多