As the title states, I'm trying to convert some floats to ints and there are a few anomalies i saw for a couple of values. I have a method that's trying to convert the decimal portion of a float, for example .45 from 123.45
, to a string representation where it outputs as 45/100
.
The problem is that for 0.35, 0.45, 0.65 and 0.95
i get 0.34, 0.44, 0.64 and 0.94
respectively. Here's my implementation:
public String convertDecimalPartToString(float input){
int numberOfDigits = numberOfDigits(input);
System.out.println(numberOfDigits);
String numerator = Integer.toString((int) (input * Math.pow(10, numberOfDigits)));
String denominator = Integer.toString((int) Math.pow(10, numberOfDigits));
return numerator + "/" + denominator;
}
public int numberOfDigits(float input){
String inputAsString = Float.toString(input);
System.out.println(inputAsString);
int digits = 0;
// go to less than 2 because first 2 will be 0 and .
for(int i =0;i<inputAsString.length()-2;i++){
digits++;
}
return digits;
}
My test method looks like this:
@Test
public void testConvertDecimalPartToString(){
float input = 0.95f;
//output is 94/100 and assert fails
Assert.assertEquals("95/100", checkWriter.convertDecimalPartToString(input));
}
It seems like there's a miscalculation in this line:
String numerator = Integer.toString((int) (input * Math.pow(10, numberOfDigits)));
but I don't understand why it works properly for 0.05, 0.15, 0.25, 0.55, 0.75 and 0.85
.
Can anybody help me understand?