【问题标题】:python comma separate values by thousands without trailing zerospython逗号将值分隔数千而不尾随零
【发布时间】:2017-08-27 03:49:30
【问题描述】:

我正在尝试用逗号分隔浮点数以千为单位。我可以使用 locale.format() 函数来做到这一点。但是预期的输出没有考虑小数点。

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
amount = locale.format('%d', 10025.87, True)
amount
'10,025'

我的预期输出应该是 10,025.87,保留尾随值。请让我知道这种情况是否可行

Value: 1067.00
Output: 1,067

Value: 1200450
Output: 1,200,450

Value: 1340.9
Output: 1,340.9

【问题讨论】:

  • %d 是整数格式代码。尝试使用 %f
  • Austin Hastings 和 manvi77,是的,它可以工作,但它会留下大量的尾随零。必须结合使用 rstrip 来删除它们。非常感谢

标签: python django floating-point number-formatting decimal-point


【解决方案1】:

这个怎么样:

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
# strip any potential trailing zeros because %f is used.
amount = locale.format('%f', 10025.87, True).rstrip('0').rstrip('.')
amount  # '10,025.87'

【讨论】:

  • 这个有效,但它不会删除“。”需要做一个额外的'.rstrip('.')'。我现在正在做的是 amount = locale.format('%f', 10025.00, True).rstrip('0').rstrip('.')
  • 是的。更新了我的答案以删除尾随 . 以防万一存在。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-22
相关资源
最近更新 更多