How to Format the Width of Floats in Java
The "float" type is one of the primitive types in the Java programming language. A float variable contains a single-precision, floating point value that has an integer part and a decimal expansion. By using built-in Java library functions, Java applications can format a float value to have a given width (that is, a given number of places) when output to a stream or a file. These capabilities are useful to generate neat tables where all numbers are lined up in columns, or to satisfy application-dependent requirements (e.g., dollar amounts formatted to two decimal places representing cents).
Instructions
-
-
1
Include the following line at the beginning of your Java code:
import java.util.*;
-
2
Create an instance of the built-in Formatter class, as in the following sample code:
Formatter myFormatter = new Formatter();
-
-
3
Format a float value into whatever format you need, as in the following sample code:
float myFloat = 46.301;
myFormatter.format("%7.2f",myFloat);
System.out.println(myFormatter);
The example will format the number for seven places, of which two are after the decimal period. The period counts as one place. The number is left-justified, with spaces added if there are fewer digits than places. Therefore, the sample float value will be formatted as " 46.30" with two spaces before the digit "4". The "Format String Syntax" Web page explains all other possible ways of formatting a float to a given width in Java.
-
1
References
- Photo Credit Hemera Technologies/AbleStock.com/Getty Images