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

后端 未结 5 985
春和景丽
春和景丽 2020-12-12 03:37

In a loop I am adding 0.10 till I reach the desired #, and getting the index. This is my code :

    private static int getIndexOfUnits(float units) {
    int         


        
相关标签:
5条回答
  • 2020-12-12 03:56

    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());
    
        }
    
    0 讨论(0)
  • 2020-12-12 04:06

    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.

    0 讨论(0)
  • 2020-12-12 04:08

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

    Use BigDecimal instead.

    0 讨论(0)
  • 2020-12-12 04:12

    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.

    0 讨论(0)
  • 2020-12-12 04:19

    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.

    0 讨论(0)
提交回复
热议问题