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)?
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.
For starters, you're trying to divide 1/4
as integer values, and it's truncating it. 1. / 4
will correctly give you 0.25
; other ways to express the number 1
as a double
include 1d
, 1.0
, and so on.
Other approaches include:
BigDecimal
to store values to an exact decimal precision. (For example, this is the preferred way to deal with monetary values.)Fraction
or Rational
class, either rolling your own or using one from a library. Apache Commons has Fraction
and BigFraction
, though their documentation seems a little sketchy.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With