在Java中:String test1 = String.format("%7.2g", 3e9);
System.out.println(test1);
打印3.0e+09
在Python2.7中,如果我运行以下代码for num in [3e9, 3.1e9, 3.01e9, 3e2, 3.1e2, 3.01e2]:
print '%7.2g %7.2f %7.2e' % (num, num, num)
我明白了3e+09 3000000000.00 3.00e+09
3.1e+09 3100000000.00 3.10e+09
3e+09 3010000000.00 3.01e+09
3e+02 300.00 3.00e+02
3.1e+02 310.00 3.10e+02
3e+02 301.00 3.01e+02
嗯?看起来,在Python的%g中,precision(.2)参数的处理方式与在Python的%f、Python的%e或Java的%g中完全不同。这里是doc(我的重点):General format. For a given precision p >= 1, this rounds the number to p significant digits and then formats the result in either fixed-point format or in scientific notation, depending on its magnitude.
The precise rules are as follows: suppose that the result formatted with presentation type 'e' and precision p-1 would have exponent exp. Then if -4 <= exp < p, the number is formatted with presentation type 'f' and precision p-1-exp. Otherwise, the number is formatted with presentation type 'e' and precision p-1. In both cases insignificant trailing zeros are removed from the significand, and the decimal point is also removed if there are no remaining digits following it.
Positive and negative infinity, positive and negative zero, and nans, are formatted as inf, -inf, 0, -0 and nan respectively, regardless of the precision.
A precision of 0 is treated as equivalent to a precision of 1. The default precision is 6.
世界贸易基金会?有什么方法可以防止那些尾随的零被删除吗?字符串格式的整个要点是实现某种一致性,例如文本对齐。
有没有什么方法可以让Java行为(本质上是小数点右边的有效位数)不必从头重写整个过程?