Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 258
ACarter Avatar asked Dec 01 '22 23:12

ACarter


2 Answers

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.

like image 107
Alex Avatar answered Dec 14 '22 23:12

Alex


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:

  • Use BigDecimal to store values to an exact decimal precision. (For example, this is the preferred way to deal with monetary values.)
  • Use a 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.
like image 23
Louis Wasserman Avatar answered Dec 15 '22 00:12

Louis Wasserman