【问题标题】:Format python decimal as [-.0-9]*, no trailing zeros, value-preserving将 python 十进制格式设置为 [-.0-9]*,没有尾随零,保留值
【发布时间】:2013-08-20 08:29:25
【问题描述】:

我正在寻找一种方法,它接受一个 decimal.Decimal 对象 x 并返回一个字符串 s,这样:

  • x == Decimal(s)
  • re.match("^-?(0|[1-9][0-9]*)(.[0-9]*[1-9])?$", s) is not None
  • s != '-0'

换句话说,该方法不会改变 Decimal 对象的值;它返回一个从不采用科学记数法的字符串表示形式(例如1e80),并且从不包含任何尾随零。

我假设有一个标准库函数可以让我这样做,但我还没有找到。你知道吗?

【问题讨论】:

  • 被骗者提出了两种解决方案,x.normalize()str(x).rstrip('0').rstrip('.');他们都失败了。 ### str(Decimal('1e-20')).rstrip('0').rstrip('.')'1e-2'Decimal('1e-2') != Decimal('1e-20'),违反了相等条件。 ### Decimal('10').normalize()'1E+1',这违反了正则表达式条件。 ### 不过,使用'{:f}'.format(x) 似乎可行。
  • 但问题完全一样,即使答案是错误的

标签: python decimal string-formatting number-formatting scientific-notation


【解决方案1】:

n.normalize() 截断精度超过 28 位的小数,但您可以使用字符串格式化和手动检查负零:

'{:f}'.format(abs(n) if n.is_zero() else n)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2011-02-12
    • 2014-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多