Floating-point cheat sheet for Java

Floating-Point Types

Java has IEEE 754 single and double precision types supported by keywords:

	float f = 0.1f; // 32 bit float, note f suffix
	double d = 0.1d; // 64 bit float, suffix optional

The strictfp keyword on classes, interfaces and methods forces all intermediate results of floating-point calculations to be IEEE 754 values as well, guaranteeing identical results on all platforms. Without that keyword, implementations can use an extended exponent range where available, resulting in more precise results and faster execution on many common CPUs.

Decimal Types

Java has an arbitrary-precision decimal type named java.math.BigDecimal, which also allows to choose the rounding mode.

	BigDecimal a = new BigDecimal("0.1");
	BigDecimal b = new BigDecimal("0.2");
	BigDecimal c = a.add(b); // returns a BigDecimal representing exactly 0.3

How to Round

To get a String:

	String.format("%.2f", 1.2399) // returns "1.24"
	String.format("%.3f", 1.2399) // returns "1.240"
	String.format("%.2f", 1.2) // returns "1.20"

To print to standard output (or any PrintStream):

	System.out.printf("%.2f", 1.2399) // same syntax as String.format()

If you don’t want trailing zeroes:

	new DecimalFormat("0.00").format(1.2)// returns "1.20"
	new DecimalFormat("0.##").format(1.2)// returns "1.2"

If you need a specific rounding mode:

	new BigDecimal("1.25").setScale(1, RoundingMode.HALF_EVEN); // returns 1.2


© Published at floating-point-gui.de under the Creative Commons Attribution License (BY)

Fork me on GitHub