Java Reference
In-Depth Information
public static void formatDouble(double myDouble){
NumberFormat numberFormatter = new
DecimalFormat("##.000");
String result = numberFormatter.format(myDouble);
System.out.println(result);
}
For instance, if the
double
value passed into the
formatDouble()
method is
345.9372
, the following will be the result:
345.937
Similarly, if the value
.7697
is passed to the method, the following will be the res-
ult:
.770
Each of the results is formatted using the specified pattern and then rounded ac-
cordingly.
How It Works
The
DecimalFormat
class can be used along with the
NumberFormat
class to
round and/or format
double
or
long
values.
NumberFormat
is an abstract class
that provides the interface for formatting and parsing numbers. This class provides the
ability to format and parse numbers for each locale, and obtain formats for currency,
percentage, integers, and numbers. By itself, the
NumberFormat
class can be very
useful as it contains factory methods that can be used to obtain formatted numbers. In
fact, little work needs to be done in order to obtain a formatted string. For example, the
following code demonstrates calling some factory methods on the
NumberFormat
class:
// Obtains an instance of NumberFormat class
NumberFormat format = NumberFormat.getInstance();
// Format a double value for the current locale
String result = format.format(83.404);
System.out.println(result);