Zoo tutorials: [ SQL | Linux | XML ]
ProgZoo: [ Java | C# | VB | C++ | Perl ]
Log in

A Gentle Introduction to
Java Programming

Possible loss of precision

 

Data types

Possible loss of precision

A double can store more decimal places than a float. This means that if convert a double to a float we will lose precision - i.e. the number will be less precise.

1. [ Java ] Possible loss of precision


Big

We cannot even compile a program that might involve a loss of precision. Attempting to (implicitly) convert a double to a float will cause a compile error such as:

Demo.java:4: possible loss of precision
found   : double
required: float
We should do one of the following:
  • Explicitly cast from double to float:
    float d = (float)3.8;
  • Use f to indicate that the literal is a float not a double

2. [ Java ] Problems with Round


Big

This is an issue with Java

We can use Math.round to convert:

  • A double to a long
  • A float to an int
In this example we try to convert a double to an int. The solution is to either:
  • Change the double to a float first:
    int i=Math.round(3.1f);
  • Change the long to an int:
    int i=(int)Math.round(3.1);