Formatters and Java Print Streams - Floating-point conversions
(Page 5 of 5 )
Floating-point conversions can be applied to all floating-point types: float and double, the type-wrapper classesFloatandDouble, andjava.math.BigDecimal. These conversions are:
%f
A regular base-10 decimal number, such as 3.141593
%e
A decimal number in scientific notation with a
lowercase e, such as 3.141593e+00
%E
A decimal number in scientific notation with an
uppercase E, such as 3.141593E+00
%g
A decimal number formatted in either regular or
scientific notation, depending on its size and
precision, with a lowercase e if scientific notation is
used
%G
A decimal number formatted in either regular or
scientific notation, depending on its size and
precision, with an uppercase E if scientific notation is
used
%a
A lowercase hexadecimal floating-point number, such
as 0x1.921fb54442d18p1
%A
An uppercase hexadecimal floating-point number,
such as 0X1.921FB54442D18P1
Surprisingly, you cannot use these conversions on integer types such asintorBigDecimal. Java will not automatically promote the integer type to a floating-point type when formatting. If you try to use them, it throws anIllegalFormatConversionException.
Example 7-2 prints π in all of these formats.
Example 7-2. Floating-point format specifiers
public class FloatingPointFormatExample {
public static void main(String[] args){
System.out.printf("Decimal: %f\n", Math.PI);
System.out.printf("Scientific notation: %e\n", Math.PI);
System.out.printf("Scientific notation: %E\n", Math.PI);
System.out.printf("Decimal/Scientific: %g\n", Math.PI);
System.out.printf("Decimal/Scientific: %G\n", Math.PI);
System.out.printf("Lowercase Hexadecimal: %a\n", Math.PI);
System.out.printf("Uppercase Hexadecimal: %A\n", Math.PI);
}
}
Here’s the output:
Decimal: 3.141593
Scientific notation: 3.141593e+00
Scientific notation: 3.141593E+00
Decimal/Scientific: 3.14159
Decimal/Scientific: 3.14159
Lowercase Hexadecimal: 0x1.921fb54442d18p1
Uppercase Hexadecimal: 0X1.921FB54442D18P1
Please check back next week for the conclusion to this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter seven of Java I/O, Second Edition, written by Elliotte Rusty Harold (O'Reilly, 2006; ISBN: 0596527500). Check it out today at your favorite bookstore. Buy this book now.
|
|