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

后端 未结 5 991
春和景丽
春和景丽 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 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.

提交回复
热议问题