Edan Chetrit
Edan Chetrit

Reputation: 5081

double being rounded and not precise

double x = 0;
double P = 0.327; //P is a actually function that return double and change all the time
double w1 = 1/4; //prints 0 (w1 and w2 are same as P)
double w2= 10/4; //prints 2
x=x+P*w1+(1-P)*w2; 
System.out.println(x); // prints 1.346 and the real result is 1.76425

i dont know how to overcome the problem of double that is rounding down, i tried the BigDecimal, maybe i just dont do it right..

i dont need very precise result but i do need the result 1.764. Thanks in advance.

Upvotes: 1

Views: 155

Answers (3)

Nambi
Nambi

Reputation: 12042

setScale and then use the ROUND_HALF_DOWN to rounding down in bigdecimal

   BigDecimal bigdecimal=new BigDecimal(x);
   bigdecimal.setScale(2, BigDecimal.ROUND_HALF_DOWN);

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691715

1 / 4 and 10 / 4 are integer divisions. Their result is an int, that is then widened to a double. What you want is a double division:

double w1 = 1.0 / 4

or

double w1 = 1 / 4.0

Upvotes: 3

BackSlash
BackSlash

Reputation: 22233

That's because you are performing integer division (1, 4 and 10 are treated as integers, so 1/4 and 1/10 will be integer divisions).

Change w1 and w2 to:

double w1 = 1/4.0;
double w2 = 10/4.0;

This way java will perform floating point division

Upvotes: 3

Related Questions