How to format number in java?

We often need to format a number in java for various reasons and in various patterns. Java provides NumberFormat and DecimalFormat classes to format number in java. Lets see how we can use these classes to format the number in java.

1. Using "00"

If we want to round up a number we can use 0 , lets see how we can achieve this, first we need to create DecimalFormat constructor with format we want to have.


NumberFormat formatter = new DecimalFormat("0000"); // To round up opeations
String nfs = formatter.format(7777.777);
System.out.println(" nfs "+ nfs);
formatter = new DecimalFormat("000000");
nfs = formatter.format(7777.777);
System.out.println(" nfs "+ nfs);

Output :

nfs 7778
nfs 007778

2. Using "##"

If we use # then it shows the number or digit, if no digit is present then it shows nothing


formatter = new DecimalFormat("##");
nfs = formatter.format(7777.777);
System.out.println(" nfs "+ nfs);
formatter = new DecimalFormat("##00");
nfs = formatter.format(7);
System.out.println(" nfs "+ nfs);
formatter = new DecimalFormat("##000");
nfs = formatter.format(7);
System.out.println(" nfs "+ nfs);

Output :

nfs 7778
nfs 07
nfs 007


3. Using "."

With using "." , we can format the number by suggesting a decimal point. "." signifies the decimal point. Lets see how we can use it to format a number.


formatter = new DecimalFormat(".00");
nfs = formatter.format(.77777);
System.out.println(" nfs "+nfs);
formatter = new DecimalFormat("0.00");
nfs = formatter.format(777.777);
System.out.println(" nfs "+nfs);
formatter = new DecimalFormat("#.#");
nfs = formatter.format(7777.777);
System.out.println(" nfs "+nfs);
formatter = new DecimalFormat("#.###");
nfs = formatter.format(777.777);
System.out.println(" nfs "+nfs);

Output :

nfs .78
nfs 777.78
nfs 7777.8
nfs 777.777

4. Using ","


Using "," we can group the numbers as follows :


formatter = new DecimalFormat("#,###,###");
nfs = formatter.format(7777.777777);
System.out.println(" nfs "+nfs);

Output :

nfs 7,778


5. Using ";"

If we are using alternate pattern for negative values then we can use ";" as follows :

formatter = new DecimalFormat("#;{#}");
nfs = formatter.format(-777.777);
System.out.println(" nfs "+nfs);

Output:

nfs {778}


6. Using " ' "

If we want to quote literal symbols in number then we can use " ' " as follows :


formatter = new DecimalFormat("'@'#");
nfs = formatter.format(777.777);
System.out.println(" nfs "+nfs);
formatter = new DecimalFormat("'num'#");
nfs = formatter.format(777.777);
System.out.println(" nfs "+nfs);

Output :

nfs @778
nfs num778

Its some of the patterns using which we can format the numbers in java.
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment