Formatting floating point numbers is a common task in software development and Java programming is no different. You often need to pretty print float and double values up-to 2 to 4 decimal places in
console, GUI or
JSP pages. Thankfully Java provides lots of convenient methods to format a floating point number up to certain decimal places. For example you can use method
printf() to format a float or double number to a output stream. However, it does not return a String. In JDK 1.5, a new static method
format() was added to the
String class, which is similar to
printf(), but returns a String. By the way there are numerous way to format numbers in Java, you can use either
DecimalFormat class, or
NumberFormat or even
Formatter class to format floating point numbers in Java. Coming back to String's format method, here is a quick example of using it :
String strDouble = String.format("%.2f", 1.23456);
This will format the floating point number
1.23456 up-to
2 decimal places, because we have used two after decimal point in formatting instruction
%.2f, f is for floating point number, which includes both
double and
float data type in Java. Don't try to use
"d" for double here, because that is used to format integer and stands for decimal in formatting instruction. By the way there is a catch here,
format() method will also arbitrarily round the number. For example if you want to format
1.99999 up-to 2 decimal places then it will return
2.0 rather than
1.99, as shown below.