Joe
Joe

Reputation: 175

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.

Upvotes: 17

Views: 49765

Answers (7)

Joy Kimaru
Joy Kimaru

Reputation: 1

You could try

double b = 0.0;
b = 317/219;

so that i can return the decimal point

Upvotes: -3

Bohemian
Bohemian

Reputation: 424993

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.

Upvotes: 29

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

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

double b = 1.0D;

Upvotes: 2

xagyg
xagyg

Reputation: 9711

Another alternative...

double b = (double)317/219;

Upvotes: 7

Ofir Luzon
Ofir Luzon

Reputation: 10908

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:

double b = 317.0/219;
System.out.println(b);

or:

double b = ((double)317)/219;
System.out.println(b);

Upvotes: 0

bellum
bellum

Reputation: 3710

This is int dividing. Write:

double b = 317.0/219;
System.out.println(b);

Upvotes: 0

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79808

This is because you have used integer literals, so you're doing an integer division.

Try writing double b = 317.0/219.0; instead.

Upvotes: 3

Related Questions