java 中fformat_理解字符串格式中的Python%g,实现Java string.format行为

在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行为(本质上是小数点右边的有效位数)不必从头重写整个过程?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值