0

The idea of this method is to convert decimal numbers to fraction numbers. The only thing that's causing a problem is the line wert = wert * 10. When I run for example 7.52 in this method I get:

7.52

75.19999999999999

751.9999999999999

7519.999999999999

75199.9999999999

... and it goes on and on like this causing more problems. What am I missing? I want it to go like this 7.52 -> 75.2 -> 752.0.

public static Eintrag toBruchzahl(double wert) {
    System.out.println(wert);
    boolean isDone = false;
    int k = 0;
    while (!isDone) {
        if (wert % 1 == 0) {
            isDone = true;
            Eintrag resultat = new Eintrag((int) wert, (int) Math.pow(10, k));
            //resultat.normalisieren();
            return resultat;
        } else {
            k++;
            wert = wert * 10;
            System.out.println(wert);
        }
    }
    return null;
}
Rafail
  • 31
  • 3
  • This is some king of Java's internal wrong precision. I suggest you to add modifier `strictfp` either on method declaration, or on class declaration. This is because, on your machine, Java extends `double`s to 80 bits, does the stuff, and shrinks them back to 64 bits, which may cause miscalculation. `strictfp` forbids it to extend&shrink – Top Sekret Dec 03 '16 at 21:26
  • okay I added strictfp to all my classes declaration - didn't help .. I guess I'm doing it wrong? – Rafail Dec 03 '16 at 21:33
  • So then I have no idea, unfortunately. I use Debian GNU/Linux with Glibc's libm and OpenJDK, and it works as expected. Maybe refer to the question this one is considered to be a duplicate of? – Top Sekret Dec 03 '16 at 21:36
  • 1
    @JakubKaszycki There's no "Java's internal wrong precision". There's a limited bit precision being used to represent infinite precision. Something every programmer needs to understand, so if you haven't read the duplicate do it now. – Kayaman Dec 04 '16 at 08:14
  • @Rafail You don't need `strictfp` here, but rounding. Read the duplicate. – Kayaman Dec 04 '16 at 08:15

0 Answers0