Context
我在Python 3中将数字作为字符串接收,并希望将它们作为字符串发送,以便保持准确性,以便upstream 服务器可以将数字作为字符串转换为decimal.Decimal
而不会损失精度.
[Admins: I have repeatedly searched Stack Overflow and other resources can cannot find anyone asking or answering this specific question.]
Question
How do I use 100 to provide the given floating point format (below)?表明这是不可能的是一个可以接受的答案.
Succinctly put, the format is just to provide at least one decimal place at all times even if that is just a trailing zero, but never to perform any rounding.个
我想可能有Formatter class的解决方案,如果有的话,这是可以接受的,但str.format
解决方案是更好的.
我很有兴趣知道f-strings是否也能做到这一点.在这种情况下,使用f字符串不是首选的答案,但了解f字符串是否可以提供这种格式会很有趣(而不只是将演示的表达式打包到f字符串中以供执行:这只是将所需的代码移到第二个求值环境中).
Required Format
把数字和int
the format must suffix 101 to whole numbers only if they are presented without any decimal places, but preserve exactly any decimal places that are presented, even if that includes trailing zeroes.区分开来
正在考虑的另一种解决方案是strip all trailing decimal places that are zeroes but leave one and only one trailing decimal zero for whole numbers (and of course preserve all non-zero decimal places without rounding).
传入的字符串可以预期为有效的int
或Decimal
.只有小数点而没有小数位的整数的特殊情况是无效的,不会发生(不需要处理"42."
).空字符串(""
)不会出现.
仅配置到大量小数位("{:.28f}".format(1)
)是不可接受的.
Demonstration
AFAIK这应该是必需的行为.使用format
查找此行为:
for number in ("42", "4200", "42.0000", "42.34", "42.3400", "42.3456"):
string = "." in number and number or number + ".0"
print(number, "=>", string)
42 => 42.0
4200 => 4200.0
42.0000 => 42.0000
42.34 => 42.34
42.3400 => 42.3400
42.3456 => 42.3456
备择
这种替代行为也是可以接受的.
for number in ("42", "4200", "42.0000", "42.34", "42.3400", "42.3456"):
string = (
number.rstrip("0")[-1] == "." and number.rstrip("0") + "0"
or "." not in number and number + ".0"
or number.rstrip("0")
)
print(number, "=>", string)
42 => 42.0
4200 => 4200.0
42.0000 => 42.0
42.34 => 42.34
42.3400 => 42.34
42.3456 => 42.3456