Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird Java math execution

Tags:

java

math

I have an weird issue. I'm trying to store the result of an equation into a double variable.

double s = (((100 + 1)*(1/3))/100 + (1/3));

This returns a value a 0 rather than .67 (the correct value calculated from a calculator). Any reason why this could happen?

Note: A solution of saying that I could just make s = .67 is not a solution,

Thanks in advance.

like image 645
Stephen D Avatar asked Sep 27 '26 01:09

Stephen D


1 Answers

The following uses integer (i.e. truncating) division, the result of which is zero:

1/3

To get floating-point division, turn either of the argument into a double, e.g.

1.0/3

Thus, the overall expression becomes:

double s = (((100 + 1)*(1./3))/100 + (1./3));

1. is the same as 1.0. Other ways to express the same number as a double are 1d and 1D.

The above expression evaluates to 0.6699999999999999.

like image 85
NPE Avatar answered Sep 28 '26 15:09

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!