让我们说
numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]
我想通过改变小数位数来输出具有固定宽度的数字,以获得这样的输出:
0.7653
10.200
100.23
500.98
有一种简单的方法吗?我一直在尝试各种%f
和%d
配置而没有运气。
答案 0 :(得分:15)
合并两个str.format
/ format
来电:
numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]
>>> for n in numbers:
... print('{:.6s}'.format('{:0.4f}'.format(n)))
... # OR format(format(n, '0.4f'), '.6s')
...
0.7653
10.200
100.23
500.98
>>> for n in numbers:
... print('%.6s' % ('%.4f' % n))
...
0.7653
10.200
100.23
500.98
或者,您可以使用slicing:
>>> for n in numbers:
... print(('%.4f' % n)[:6])
...
0.7653
10.200
100.23
500.98
答案 1 :(得分:2)
不幸的是,这个问题没有开箱即用的解决方案。此外,使用字符串切片的解决方案不能充分处理舍入和溢出。
因此,似乎必须编写一个这样的函数:
// simple MCVE example class that mocks the functioning of your class
public class MockCopyService extends SwingWorker<Void, Integer> {
public static final String COPY = "copy";
private List<File> fileList = new ArrayList<>();
public MockCopyService() {
}
public int getFileListSize() {
// the real return:
// return fileList.size();
// the mock return:
return 10;
}
public void copyImagesToTempFolder() {
for (int i = 0; i < getFileListSize(); i++) {
System.out.println("copying file");
int fileProgress = (100 * i) / getFileListSize();
// notify listeners
setProgress(fileProgress);
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
setProgress(getFileListSize());
}
@Override
protected Void doInBackground() throws Exception {
copyImagesToTempFolder();
return null;
}
}
产生的行为:
def to_fixed_width(n, max_width, allow_overflow = True, do_round = True):
if do_round:
for i in range(max_width - 2, -1, -1):
str0 = '{:.{}f}'.format(n, i)
if len(str0) <= max_width:
break
else:
str0 = '{:.42f}'.format(n)
int_part_len = str0.index('.')
if int_part_len <= max_width - 2:
str0 = str0[:max_width]
else:
str0 = str0[:int_part_len]
if (not allow_overflow) and (len(str0) > max_width):
raise OverflowError("Impossible to represent in fixed-width non-scientific format")
return str0
更多例子:
>>> to_fixed_width(0.7653, 6)
'0.7653'
>>> to_fixed_width(10.2, 6)
'10.200'
>>> to_fixed_width(100.2325, 6)
'100.23'
>>> to_fixed_width(500.9874, 6)
'500.99'
>>> to_fixed_width(500.9874, 6, do_round = False)
'500.98'