AI Hints
Home›Java Tutorial›double and float, Arithmetic, Division and Remainder
Java · Lesson 13 of 120

double and float

Numbers with decimals.

⏱ 2 min read▶ Video at 16:41🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Prices, distances, and temperatures often have decimals. Java stores those in a double, or sometimes in a float.

  • Prices, distances
  • Have decimals
  • double or float

Working with decimals

A double holds a decimal number. Multiplying it works as you'd expect. One point zero divided by three, gives a long decimal. A float has fewer digits, so it's less exact. And finally, zero point one plus zero point two. Run it. The total is seven point five. The double third has many more digits than the float. And zero point one plus zero point two isn't exactly zero point three!

Main.javajava
public class Main {
    public static void main(String[] args) {
        double price = 2.50;
        double total = price * 3;
        System.out.println("Total: " + total);

        double third = 1.0 / 3;
        System.out.println("A third: " + third);
        float f = 1.0f / 3;
        System.out.println("As float: " + f);

        System.out.println(0.1 + 0.2);
    }
}
Output
Total: 7.5
A third: 0.3333333333333333
As float: 0.33333334
0.30000000000000004

Why 0.1 + 0.2 looks wrong

Computers store decimals in binary, and some decimals, like zero point one, can't be stored exactly. So tiny errors appear. It's the same in almost every language. For money, many programs count in whole cents, or use a class called BigDecimal.

keyvalue
Causebinary can't store 0.1 exactly
Everywherenot just Java
Moneycount cents as long
OrBigDecimal

double or float

Double has about fifteen accurate digits, and it's the normal choice. Float has about seven, and needs an f on the end. Use double, unless you have a special reason not to.

double

  • About 15 digitsThe default4.99

float

  • About 7 digitsNeeds f4.99f

Summary

Use double for decimals. Tiny rounding errors are normal, so count money in cents. Next, arithmetic.

Key takeaways
  • double is the default
  • float needs f
  • 0.1 + 0.2 ≈ 0.3
Next up: Arithmetic — plus, minus, times