1

Is this a bug in jvm the code bellow gives the result : 409.99999999999994 !

public class HelloWorld{
     public static void main(String []args){
          double d = 4.10d;
          double d2 = d * 100d ;
          System.out.println(d2);
     }
 }

changing double by float solves the problem, but why?

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Lhoussin Ghanem
  • 179
  • 1
  • 8

1 Answers1

2

Computers use a finite amount of bits to represent numbers, so it's not possible to represent them all exactly. What you're seeing is the result of rounding to numbers the computer can actually represent.

What Every Computer Scientist Should Know About Floating-Point Arithmetic is a good read since this is your first time seeing this.

Alfred Rossi
  • 1,942
  • 15
  • 19