When I divide 317 by 219 in Java using doubles I get 1.
For example:
double b = 317/219;
System.out.println(b);
Output is: 1.
Is this because it is a recurring decimal? Have had to use BigDecimal instead which is annoying.
When I divide 317 by 219 in Java using doubles I get 1.
For example:
double b = 317/219;
System.out.println(b);
Output is: 1.
Is this because it is a recurring decimal? Have had to use BigDecimal instead which is annoying.
This is because you have used integer literals, so you're doing an integer division.
Try writing
double b = 317.0/219.0;
instead.Try this
The default type of coded numbers in java is
int
, so with the code as you have it java is working with twoint
numbers and the result of the division would then beint
too, which will truncate the decimal part to give a final result of1
. Thisint
result is then cast fromint 1
to adouble 1
without a compiler warning because it's a widening cast (one where the source type is guaranteed to "fit" into the target type).By coding either of the numbers as
double
with the trailingD
(you may also used
, but I always use upper case letters becauseL
as lowercasel
looks like a1
), the result of the division will bedouble
too.It is worth mentioning that there is no division in your example at runtime. 317/219 is calculated at compile-time (integer division, fraction is discarded) and replaced with a constant. If you decompile .class (I used Jad http://www.kpdus.com/jad.html) you will see
since numbers you put are inetgers so is the answer.
to get double you need either to use a number with floating point or to cast one of the integers you use:
or:
This is
int
dividing. Write:Another alternative...