5 Examples of Formatting Float or Double Numbers to String in Java

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.


String strDouble = String.format("%.2f", 1.9999); System.out.println(strDouble); // print 2.00


As I said before, this is not the only way to format floating point numbers in Java, you can use right from the top Formatter class, which provides format() method similar to String's format() method. Alternatively, if you just want to print formatted floating point numbers into console, you can use System.printf() method, which effectively combine above two lines into single one.

But the best method for task is using DecmialFormat class, which is actually designed to format any number in Java be it integer, float or double. While creating instance of DecimalFormat class, you can pass it a formatting string, which is bit different then what you pass to these format method, but I guess its more readable. This string specifies up-to how many decimal places you want to format the input. Here is a quick example of formatting double and float numbers using DecimalFormat class.
DecimalFormat df = new DecimalFormat("#.##");
String formatted = df.format(2.456345); 
System.out.println(formatted);  //prints 2.46
The string "#.##" indicate that we are formatting up-to 2 decimal points, "#.###" indicates formatting number up-to 3 decimal places. By the way, even DecimalFormat rounds the number if next decimal point is more than 5.

By the way, there is subtle difference between formatting floating point numbers using String.format() and DecimalFormat.format(), former will always print trailing zeros even if there is no fractional part. For example if you format 2.00034 up-to two decimal places String's format() method will print "2.00", while format() method of DecimalFormat class will print "2", as shown below :
String strDouble = String.format("%.2f", 2.00023);  
System.out.println(strDouble); // print 2.00
        
DecimalFormat df = new DecimalFormat("#.##");
String formatted = df.format(2.00023); 
System.out.println(formatted);  //prints 2
This is a very subtle but useful difference, its easy to forget but pays well when you remember it. You can now decide what to use depending upon whether you need trailing zeros or not.



Formatting Floating Point Number in Java

format numbers upto 2 to 3 decimal places in Java
Here is our complete Java program to format floating point numbers in Java. It includes all the ways, we have discussed so far to format a float or double variable up-to certain decimal places in Java. You can use any of these technique to pretty print any float or double variable in Java. I personally like to use DecimalFormat for its readability advantage but like SimpleDateFormat, this is also an expensive object and not thread-safe, so use this with caution. One more thing to consider is trailing zeros, if you want trailing zeros e.g. want to print 2 as "2.00" then use String class' format method, otherwise use DecimalFormat's format method. Most of the time you can use a local instance of DecimalFormat, but if performance is critical for your application then you either need to explicitly synchronize access of this object or use a ThreadLocal variable, which is more efficient, and avoids cost of acquiring and releasing locks. Now, it's time to see our code example.

import java.util.Arrays;
import java.util.Formatter;
 
/**
* Java program to format float or double to String in Java. In this Java
* example, you will learn how to display a floating point number up-to 2 or 3
* decimal places.
*
* @author Javin Paul
*/
public class FormatFloatInJava {
 
    public static void main(String args[]) {
 
        // First task - format a floating point number up-to 2 decimal places
        float pi = 3.1428733f;
 
        // From Java 5, String has a format() method
        String str = String.format("%.02f", pi);
        System.out.println("formatted float up to 2 decimals " + str);
 
        // If you just want to display, you can combine above two by using printf()
        // syntax of formatting will remain same
        // this will display floating point number up-to 3 decimals
        System.out.printf("floating point number up-to 3 decimals : %.03f %n", pi);
 
        // Alternatively you can also use Formatter class to format floating point numbers
        // Allocate a Formatter on the StringBuilder
        StringBuilder sb = new StringBuilder();
        Formatter formatter = new Formatter(sb);  // Send all outputs to StringBuilder
 
        // format() has the same syntax as printf()
        formatter.format("%.4f", pi);     // 4 decimal places
        System.out.println("Value of PI up to four decimals : " + formatter.toString());
        formatter.close();
 
        // Similarly you can format double to String in Java
        double price = 20.25;
        System.out.printf("Value of double up-to 2 decimals : %.2f", price);
 
       // best way to format floating point numbers in Java
       // beware it also round the numbers
      DecimalFormat df = new DecimalFormat("#.##");
      String formatted = df.format(2.456345); 
      System.out.println(formatted);  //prints 2.46

    }
 
}
 
Output:
formatted float up-to 2 decimals 3.14
floating point number up-to 3 decimals : 3.143
Value of PI up to four decimals : 3.1429
Value of double up-to 2 decimals : 20.25
2.46

I just remember there is another way to pretty print floating point number in Java, by using setMaximumFractionDigits(int places) method form NumberFormat class. you can just pass number of digit you want to keep decimals, for example to format a number up-to 4 decimal places, pass 4. Here is a quick example of this :
double simple = 4.0099;
double round = 4.9999;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(3);
System.out.println(nf.format(simple)); // prints 4.01
System.out.println(nf.format(round));  // prints 5

That's all about how to format floating point numbers in Java. We have seen following four ways to format a float or double number as String in Java :

  1. By using String format() method
  2. By using DecimalFormat format() method
  3. By using printf() method 
  4. By using Formatter's format() method
  5. By using setMaximumFractionDigits() of NumberFormat class

You can use any of these approaches to format floating point numbers, just remember that String's format() will always print trailing zeros even if there is no more fractional part, while DecimalFormat, NumberFormat classes will not keep that. 

No comments:

Post a Comment