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
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());
}
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.
The problem is that the format that float uses can't represent all decimal numbers, so precision is lost sometimes.
Use BigDecimal instead.
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.
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.