1
double price = 4.35; 
double quantity = 100; 
double total = price * quantity;   // Should be 100 * 4.35 = 435.00 
System.out.println(total); // Prints 434.99999999999999

Why does this happen?

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332

2 Answers2

0

The multiplication is working fine, but 4.35 cannot be represented exactly as a double.

Check the floating point Internal Representation.

Wiki says:-

The fact that floating-point numbers cannot precisely represent all real numbers, and that floating-point operations cannot precisely represent true arithmetic operations, leads to many surprising situations. This is related to the finite precision with which computers generally represent numbers.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

Because precision for a double is like something like:

Double-precision floating-point format is a computer number format that occupies 8 bytes (64 bits) in computer memory and represents a wide dynamic range of values by using floating point. Computers with 32-bit storage locations use two memory locations to store a 64-bit double-precision number (a single storage location can hold a single-precision number). Double-precision floating-point format usually refers to binary64, as specified by the IEEE 754 standard, not to the 64-bit decimal format decimal64.

So your value 4.35 is not exactly stored as 4.35, rather it is stored with precision

Source: Wiki

Have a look here

Shailesh Saxena
  • 3,472
  • 2
  • 18
  • 28