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

后端 未结 5 989
春和景丽
春和景丽 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());
    
        }
    

提交回复
热议问题