0

Could someone help me what is happening here? Why java compiler returns 869 from the below example?

package week1;

public class PercentagePrinter {
    public static void main(String[] args){

        double probability = 8.70;
        int percentage = (int)(100 * probability);
        System.out.println(percentage);
    }

}
  • What is happening here is that you're using floating point numbers. Floating point numbers are bad. Do not use floating point numbers. – RaminS Oct 08 '16 at 15:42
  • @Gendarme That is nonsense. They are just a bit tricky to handle. Under certain circumstances, they are bad (e. g. if you deal with money), but not generally. – glglgl Oct 12 '16 at 07:15

1 Answers1

0

Using double you are losing precision, like when you hold the value of 8.7 it is represented as something like 8.6999... so when you are converting the value to int after the multiplication, you get only 8.69. You can use breakpoints and see the actual value of probability by the execution of your program.

glglgl
  • 89,107
  • 13
  • 149
  • 217
meJustAndrew
  • 6,011
  • 8
  • 50
  • 76