java损失精度,Java精度损失

I have a problem concerned with losing of precision

my task is to print numbers as strings

int exponent = ...

int[] Mantissas = { 1, 2, 5 };

double dataStep = java.lang.Math.pow(10.0, exponent) * Mantissas[mantissaIndex];

...

for (int i = 0; i < NSteps; i++)

steps[i] = firstStep + i * dataStep;

draw(steps);

for example, 0.2*7=1.4000000000000001; 0.0000014/10=1.3999999999999998E-7

how to figure out this problem?

UPD: The main problem is string output formating. i don't bother about losting of about 0.00000001 value.

Now I solved it as String.format("%f", value),

but I think it's not good approach

解决方案

As mentioned by others you have to use java.math.BigDecimal instead of float/double. This however comes with its own set of problems.

For instance when you call BigDecimal(double) the value you pass in will be expanded to its full representation:

BigDecimal oneTenth = new BigDecimal(0.1);

BigDecimal oneMillion = new BigDecimal(1000000);

oneTenth.multiply(oneMillion)

out> 100000.0000000000055511151231257827021181583404541015625000000

But when you use the BigDecimal(String) constructor the eact value is represented and you get

BigDecimal oneTenth = new BigDecimal("0.1");

BigDecimalr oneMillion = new BigDecimal(1000000);

oneTenth.multiply(oneMillion)

out> 100000.0

You can read more on BigDecimal's limitations in Joshua Bloch and Neal Gafter's splendid Java puzzlers book and in this informative article. Finally note that toString on BigDecimal's will print in scientific notation so you will properly have to use toPlainString instead.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值