4

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ACarter
  • 5,688
  • 9
  • 39
  • 56
  • And to answer your second question, http://stackoverflow.com/questions/5442640/is-there-a-commonly-used-rational-numbers-library-in-java suggests alternatives if you (as it sounds like) actually want rational numbers, rather than floating point division – AakashM Feb 13 '12 at 09:13
  • And SO works best if you keep it to one question per post, for exactly this reason. – Teepeemm Dec 09 '15 at 15:26
  • If you really want to retain that fraction/rational number character, without truncation, you should write a Fraction or Rational class that has numerator and denominator private members and all the methods you'd want to execute on it: add, sub, mul, div, etc. – duffymo Dec 10 '19 at 13:48

4 Answers4

13

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.

stkent
  • 19,772
  • 14
  • 85
  • 111
Alex
  • 2,106
  • 16
  • 15
4

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.
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

Java is performing integer division because your denominator is an integer.

Try the following:

double quarter = 1 / 4.0;

Or:

double quarter = 1 / (double) 4;
Dylan Knowles
  • 2,726
  • 1
  • 26
  • 52
1

The reason you're getting 0.0 is because the division is done as an integer division and then the result is converted to float. Try this, for example: double quarter = 1.0/4.0; - you should get (pretty much) the expected result.

However, depending on your requirements, this may not be the best way to deal with the problem. For example, you can't store 1/3 in a decimal. The perfect way would be to store simple fraction as a pair of integers. You can create a class for it (with some arithmetic methods) or start by using a simple array. It all depends on your needs.

Aleks G
  • 56,435
  • 29
  • 168
  • 265