Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd behaviors when dividing doubles in Java

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.

like image 661
Joe Avatar asked Dec 02 '12 09:12

Joe


2 Answers

Try this

 double b = 317/219D;

The default type of coded numbers in java is int, so with the code as you have it java is working with two int numbers and the result of the division would then be int too, which will truncate the decimal part to give a final result of 1. This int result is then cast from int 1 to a double 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 trailing D (you may also use d, but I always use upper case letters because L as lowercase l looks like a 1), the result of the division will be double too.

like image 128
Bohemian Avatar answered Nov 05 '22 07:11

Bohemian


Another alternative...

double b = (double)317/219;
like image 21
xagyg Avatar answered Nov 05 '22 06:11

xagyg