1

In java:

double b = 1234 / (1234+1500);

result is:

0.0

why?

How to get correct result?

serenesat
  • 4,611
  • 10
  • 37
  • 53

3 Answers3

1
double b = 1234D / (1234D + 1500D)
Steve
  • 363
  • 2
  • 11
  • but i am using an local variable to give input value... how to implement it –  Apr 01 '15 at 12:26
  • I only answered your original question. To be honest, I would not use doubles for arithmetic. Use BigDecimals and parse your inputs to them – Steve Apr 01 '15 at 12:30
0

just make one of the operand double/float -

double b = (double) 1234.0/(1235+1500);

Here casting is not required.

The rules benind: if one of the operand is double/float (here 1234.0) the other is promoted to double/float.

Razib
  • 10,965
  • 11
  • 53
  • 80
0

You get 0.0 because java will be an integer devision. To get the correct result you have to cast at least on operator to double.

double b = ((double)1234) / (1234+1500)
Jens
  • 67,715
  • 15
  • 98
  • 113