0% found this document useful (0 votes)
138 views

The Floating-Point Guide - Floating-Point Cheat Sheet For Java

Floating point guide

Uploaded by

Ranjith M Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
138 views

The Floating-Point Guide - Floating-Point Cheat Sheet For Java

Floating point guide

Uploaded by

Ranjith M Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

The Floating-Point Guide - Floating-point cheat sheet for Java

1 of 2

http://floating-point-gui.de/languages/java/

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 dont 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

Resources
Java Language Specification
Floating-Point Types, Formats, and Values
Java Standard API
1/6/2015 9:44 AM

The Floating-Point Guide - Floating-point cheat sheet for Java

2 of 2

http://floating-point-gui.de/languages/java/

BigDecimal
DecimalFormat
String.format()

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

The Floating-Point Guide


Home
Basic Answers
References
xkcd

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

You might also like