java输出精度,java-在控制台中输出时的浮点精度

float x = 0.98123452f;

System.out.println(x); //it prints out 0.9812345

float x = 0.98123453f;

System.out.println(x); //it prints out 0.98123455

I have no idea why the second one's output is 0.98123455 instead of 0.9812345. Isn't the precision of float is 7 decimal digits?

解决方案

The IEEE 754 float representation of

0.98123453

is 32 bits of (sign, exp, mantissa):

0 01111110 11110110011001000110000

which is:

0.9812345504760742

in double precision, and cast back to float decimal representation:

0.98123455

The number of bits allocated to a single precision (float) is 32, and 64 bits for double precision. Further note that BigDecimal that is frequently suggested will store your number as a string, and not in IEEE754 format. It will do a conversion when it needs to act on the number, and while it has a better precision, it is awfully slow.

EDIT. To clarify why it prints 0.98123455, we need to observe that it is the closest single precision representation of the number 0.98123453:

00111111011110110011001000101111 = 0.9812345 (sp) = 0.9812344908714294 (dp)

00111111011110110011001000110000 = 0.98123455 (sp) = 0.9812345504760742 (dp)

00111111011110110011001000110001 = 0.9812346 (sp) = 0.981234610080719 (dp)

sp = single precision, dp = double precision

The listing is for the [-1,+1] binary range around the number, and you can see that 0.98123453 is closest to the 10000 suffix of the mantissa, while 0.98123452 is closest to the 01111 suffix.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值