0

I am trying to extract only the decimal digits in a number (e.g. 4.375 becomes 0.375). For this purpose I wrote this snippet of code, that works mostly as expected, except for the last float.

float[] actualSizes = {4.375f, 4.375f, 6.5625f, 8.75f, 10.93f};
float decimalDigits;

for (int i = 0; i < actualSizes.length; i++) 
{
        decimalDigits = actualSizes[i] - (int)(actualSizes[i]);
        System.out.println(decimalDigits);
}

Here is the output, I expected the last line to be 0.93:

0.375
0.375
0.5625
0.75
0.9300003

I have tried the same using double, and the result is again not the one expected. I think the problem might be along the lines of the one described in the question Is floating point math broken? (The question is for Javascript, while I'm using Java).

Is there a way to get around this in my program and get that 0.93?

Marti
  • 21
  • 7
  • I was wondering whether there is a way to obtain the decimal places of a number without incurring in that problem. Do you know how I could do that? – Marti Feb 26 '18 at 13:39
  • @Marti You're not understanding what is being explained in the answer. The outputs you got are correct. – Neijwiert Feb 26 '18 at 13:41
  • Actually, this question is substantially different from “Is floating-point broken”, in that `10.93f-10.0f` is an exact operation and that the weirdness comes from Java's weird choice when printing floats with `System.out.println`. What is true and that you should get from “is floating…” is that when you write `10.93f`, the number you get is not 1093/100. You can print the number you get to any number of decimal places. Subtracting 10 from it is exact. You can print the result to any number of decimal places. Can you tell how many you want? – Pascal Cuoq Feb 26 '18 at 13:43
  • @Marti Funny thing is, all but the last one of your test values have something in common when expressed as simple ratios. Try adding more values with denominators not powers of two. – bipll Feb 26 '18 at 13:47
  • @PascalCuoq How so? The arithmetic can't properly store true 0.93. How could it possibly know you wanted to print out 0.93 instead of the real representation? – Neijwiert Feb 26 '18 at 13:47
  • @Neijwiert How so what? And where did I claim that “it” coud possibly know you wanted to print out 0.93? What is “it”? – Pascal Cuoq Feb 26 '18 at 14:44
  • @PascalCuoq I thought you meant something differently before. You edited your comment, which cleared things up. By "it" I just mean the machine executing the code. – Neijwiert Feb 26 '18 at 14:59

0 Answers0