double or float datatype doesn't addup properly in a loop?

孤人 提交于 2019-11-28 14:25:32

From the Floating-Point Guide:

Why don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and instead I get a weird result like 0.30000000000000004?

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

You cnnot use float or double if you need numbers to add up exaclty. Use BigDecimal instead.

The problem is that the format that float uses can't represent all decimal numbers, so precision is lost sometimes.

Use BigDecimal instead.

Exact representation is not available with Float datatype.

BigDecimal will help you.Below example might be helpful for you

BigDecimal decimal=new BigDecimal(10.0);
    for (int i = 0; i < 10; i++) {
        decimal=decimal.add(new BigDecimal(.1));
        System.out.println(decimal.floatValue());

    }

You shouldn't use float's for this kind of thing (indexing / iterating).

Try calculating I every time:

I = 1.0f + (i*addup);

And you'll not accumulate floating-point errors.

I think this may be what you're looking for:

Java provides a class from the import package: import java.text.DecimalFormat called DecimalFormat. Its signature is:

DecimalFormat myFormat = new DecimalFormat("0.0");

It takes a String argument where you specify how you want the formatting to be displayed.

Here's how you can apply it to your code:

DecimalFormat myFormat;
private static int getIndexOfUnits(float units) {
myFormat = new DecimalFormat("0.0");
int index = -1;
float addup = 0.10f;
for(float i = 1.00f; i < units; i=(float)i+addup) {
    index++;
    System.out.println("I = " + myFormat.format(i) + " Index = " + index);
}

return index;

}

In your println, you can see that the DecimalFormat's class format() method is called on float i using the myFormat object reference to DecimalFormat - this is where the formatting takes place.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!