Python十进制格式

用这种方法格式化一个python小数是一个好方法吗?

1.00 – >'1'
1.20 – >'1.2'
1.23 – >'1.23'
1.234 – >'1.23'
1.2345 – >'1.23'

如果你有Python 2.6或更新版本,请使用format

 '{0:.3g}'.format(num) 

对于Python 2.5或更高版本:

 '%.3g'%(num) 

说明:

{0}告诉format打印第一个参数 – 在这种情况下, num

冒号(:)后的所有内容都指定了format_spec

.3将精度设置为3。

g删除不重要的零。 见http://en.wikipedia.org/wiki/Printf#fprintf

例如:

 tests=[(1.00, '1'), (1.2, '1.2'), (1.23, '1.23'), (1.234, '1.23'), (1.2345, '1.23')] for num, answer in tests: result = '{0:.3g}'.format(num) if result != answer: print('Error: {0} --> {1} != {2}'.format(num, result, answer)) exit() else: print('{0} --> {1}'.format(num,result)) 

产量

 1.0 --> 1 1.2 --> 1.2 1.23 --> 1.23 1.234 --> 1.23 1.2345 --> 1.23 

贾斯丁的答案只有第一部分是正确的。 使用“%.3g”不适用于所有情况,因为.3不是精度,而是总位数。 尝试像1000.123这样的数字,它会中断。

所以,我会用Justin的build议:

 >>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.') '12340.1235' >>> ('%.4f' % -400).rstrip('0').rstrip('.') '-400' >>> ('%.4f' % 0).rstrip('0').rstrip('.') '0' >>> ('%.4f' % .1).rstrip('0').rstrip('.') '0.1' 

这里有一个函数可以做到这一点:

 def myformat(x): return ('%.2f' % x).rstrip('0').rstrip('.') 

这里是你的例子:

 >>> myformat(1.00) '1' >>> myformat(1.20) '1.2' >>> myformat(1.23) '1.23' >>> myformat(1.234) '1.23' >>> myformat(1.2345) '1.23' 

编辑:

从看别人的回答和试验,我发现g为你做了所有剥离的东西。 所以,

 '%.3g' % x 

也很出色,与其他人的build议略有不同(使用'{0:.3}'.format()东西)。 我想你的select。

只需使用Python的标准string格式化方法即可 :

 >>> "{0:.2}".format(1.234232) '1.2' >>> "{0:.3}".format(1.234232) '1.23' 

如果您使用的是2.6以下的Python版本,请使用

 >>> "%f" % 1.32423 '1.324230' >>> "%.2f" % 1.32423 '1.32' >>> "%d" % 1.32423 '1'