【问题标题】:Suppress scientific notation with locale.format() [duplicate]使用 locale.format() 抑制科学记数法 [重复]
【发布时间】:2022-01-21 18:18:08
【问题描述】:

我使用locale.format() 将数字分隔为逗号,但该功能并没有摆脱科学记数法。我想要一种方法来返回一个以逗号分隔的数字,带有尾随零且没有科学记数法。

实际代码示例:1160250.1294254328 -> 1.16025e+06

我想要的示例:1160250.1294254328 -> 1,160,250.13

我的代码:

locale.setlocale(locale.LC_ALL, 'en_US.utf8')

x = 1160250.1294254328
x = round(x, 2)
x = locale.format("%g", x, grouping=True, monetary=True)

【问题讨论】:

标签: python floating-point formatting locale number-formatting


【解决方案1】:

尝试使用 f 字符串:

x = 1160250.1294254328
x = round(x, 2)
print(f"{x:,}") # -> Output: 1,160,250.13

【讨论】:

    【解决方案2】:

    我第一次看到那个语言环境包给我。

    借此机会研究了locale包,发现这个包与字符串格式化操作有很大关系。

    %g 仅用于指数浮点格式。

    因此,对于你想要的格式,最好使用下面的格式。

    import locale
    
    locale.setlocale(locale.LC_ALL, 'en_us.utf-8')
    x = 1160250.1294254328
    x = locale.format("%.2f", x, grouping=True, monetary=True)
    
    print(x)
    

    如果您对字符串格式化运算符感兴趣,请查看下面的链接。

    https://python-reference.readthedocs.io/en/latest/docs/str/formatting.html

    【讨论】:

      猜你喜欢
      • 2017-03-13
      • 2013-07-18
      • 2020-05-31
      • 2021-03-17
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      相关资源
      最近更新 更多