Python 浮点格式设置为小数点后3位或4位
我想将浮点格式严格设置为小数点后3或4位 例如:Python 浮点格式设置为小数点后3位或4位,python,floating-point,rounding,Python,Floating Point,Rounding,我想将浮点格式严格设置为小数点后3或4位 例如: 1.0 => 1.000 # 3DP 1.02 => 1.020 # 3DP 1.023 => 1.023 # 3DP 1.0234 => 1.0234 # 4DP 1.02345 => 1.0234 # 4DP 类似于“{.5g}.formatmy_float”和“{.4f}.formatmy_float”的组合 有什么想法吗?假设我理解您的要求,您可以将其
1.0 => 1.000 # 3DP
1.02 => 1.020 # 3DP
1.023 => 1.023 # 3DP
1.0234 => 1.0234 # 4DP
1.02345 => 1.0234 # 4DP
类似于“{.5g}.formatmy_float”和“{.4f}.formatmy_float”的组合
有什么想法吗?假设我理解您的要求,您可以将其格式设置为4,然后删除尾随的“0”(如果有)。像这样:
def fmt_3or4(v):
"""Format float to 4 decimal places, or 3 if ends with 0."""
s = '{:.4f}'.format(v)
if s[-1] == '0':
s = s[:-1]
return s
>>> fmt_3or4(1.02345)
'1.0234'
>>> fmt_3or4(1.023)
'1.023'
>>> fmt_3or4(1.02)
'1.020'
假设我理解您的要求,您可以将其格式化为4,然后删除尾随的“0”(如果有)。像这样:
def fmt_3or4(v):
"""Format float to 4 decimal places, or 3 if ends with 0."""
s = '{:.4f}'.format(v)
if s[-1] == '0':
s = s[:-1]
return s
>>> fmt_3or4(1.02345)
'1.0234'
>>> fmt_3or4(1.023)
'1.023'
>>> fmt_3or4(1.02)
'1.020'
问题是1.023并不完全是1.023。这意味着你无法从数字本身判断它应该有3位还是4位小数。对不起,我的例子有点简单。该行为需要适用于1.02300000000001或1.02299999997等,它们都在4DP中四舍五入到1.0230,在我的情况下,我希望四舍五入到3DP。问题是1.023并不完全是1.023。这意味着你无法从数字本身判断它应该有3位还是4位小数。对不起,我的例子有点简单。该行为需要适用于1.02300000000001或1.02299999997,它们都在4DP中四舍五入到1.0230,在我的情况下,我希望四舍五入到3DP。