Search code examples
javamathfloating-pointprimitive-types

Using Java doubles (or anything else) to store simple fractions


This seems like a very simple error:

double quarter = 1/4;

Is giving

0.0

Anybody know why this might be happening?

I am trying to store pretty much all the fractions from 1/2 to 1/20 (Just the ones with 1 on the top and in int on the bottom), so I won't be able to input the decimal straight away for all of them.

I've read and heard that floating-point datatypes are not a good way of storing fractions, so is there any other way (in Java)?


Solution

  • Try:

    double quarter = 1d/4d;
    

    The division of two integers gives a truncated integer. By putting the d behind the numbers you are casting them to doubles.