截取
- Java
public static String floatToStringByTruncate(float num, int remainBitNum) {
String numStr = Float.toString(num);
BigDecimal bd = new BigDecimal(numStr);
bd = bd.setScale(remainBitNum,BigDecimal.ROUND_DOWN);
return bd.toString();
}
- Python
def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '{}'.format(f)
if 'e' in s or 'E' in s:
return '{0:.{1}f}'.format(f, n)
i, p, d = s.partition('.')
return '.'.join([i, (d+'0'*n)[:n]])
print "1.23456--%s" % truncate(1.23456, 2)
print "1.23456--%s" % truncate(1.23456, 3)
print "1.23456--%s" % truncate(1.23456, 4)
print "1.23456--%s" % truncate(1.23456, 6)
结果为:
1.23456--1.23
1.23456--1.234
1.23456--1.2345
1.23456--1.234560
同事自己实现了一个,我觉得挺好的,代码如下:
def str_format(jing):
jin_t1 = '{:.5f}'.format(float(jing))
pos = jin_t1.rfind('.')
jing_ = jing[:pos+5]
jing_ = '{:.4f}'.format(float(jing_))
return jing_
四舍五入
- Java
public static String doubleToStringByRound(double num, int remainBitNum) {
String numStr = Double.toString(num);
BigDecimal bd = new BigDecimal(numStr);
bd = bd.setScale(remainBitNum, BigDecimal.ROUND_HALF_UP);
return bd.toString();
}
参考资料:
http://stackoverflow.com/questions/783897/truncating-floats-in-python
http://segmentfault.com/a/1190000002886883
http://liuzidong.iteye.com/blog/1172248