-2

We are having some problems with calculations (divisions) in Java.

A sample program to show the problem:

public class NumberTest {

    public static void main(String[] args) {
        System.out.println("Double value: " + 27.8625d);
        System.out.println("Float value: " + 27.8625f);
        System.out.println("Double value: " + 1000.0d);
        System.out.println("Float value: " + 1000.0f);
        System.out.println("Double calculation: " + 27.8625d/1000.0d);
        System.out.println("Float calculation: " + 27.8625f/1000.0f);
    }

}

Output:

Double value: 27.8625  
Float value: 27.8625  
Double value: 1000.0  
Float value: 1000.0  
Double calculation: 0.027862500000000002  
Float calculation: 0.027862499

I would expect the result of the calculations to be "0.0278625". Why is there a different result for both the float and double calculation?

Regards,

Tim

ramaral
  • 6,149
  • 4
  • 34
  • 57
Tim
  • 56
  • 1
  • 4

2 Answers2

2

The short answer is: floating point value is stored in x * 2^y format. float uses less space (typically 4 bytes) than double (typically 8 bytes), hence there's a limited precision each of this data type can hold.

Typically when working with floating point you have to set a pre-determined precision. For example, rather than blindly printing the toString() value of the floating point, format them up to 5 digits after decimal: String.format("%.5f", value)

But there's heaps more to learn about floating point: What Every Computer Scientist Should Know About Floating-Point Arithmetic

gerrytan
  • 40,313
  • 9
  • 84
  • 99
-2

This is because the precision of both the calculation is different. If you need desired result than you can use

System.out.println(BigDecimal.valueOf(27.8625).divide(BigDecimal.valueOf(1000.0)).doubleValue());
Sanjeev
  • 9,876
  • 2
  • 22
  • 33