The Floating-Point Guide - Floating-Point Cheat Sheet For Java
The Floating-Point Guide - Floating-Point Cheat Sheet For Java
1 of 2
http://floating-point-gui.de/languages/java/
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"
Resources
Java Language Specification
Floating-Point Types, Formats, and Values
Java Standard API
1/6/2015 9:44 AM
2 of 2
http://floating-point-gui.de/languages/java/
BigDecimal
DecimalFormat
String.format()
Number Formats
Binary Fractions
Floating-Point
Exact Types
On Using Integers
Errors
Rounding
Comparison
Propagation
Language
cheat sheets
C#
Java
JavaScript
Perl
PHP
Python
Ruby
SQL
1/6/2015 9:44 AM