How to Format an Integer in Java
The Java programming language is good at storing numbers, but often numbers must be printed in a certain format. For example, currency is expected to be preceded by a currency symbol and have an appropriate number of decimal places, and often commas are used to mark every three or four digits (depending on your culture) of a large number.
Instructions
-
-
1
Open "Netbeans" and select "File" and "New class."
-
2
Type "psvm" to create a main method.
-
-
3
Add the following to the main method:
// Format integer
String s = integerFormat(i);
System.out.println(s);
This will format an integer using a method named "integerFormat." However, that method doesn't exist yet, so you will define it in the next step.
-
4
Add the following outside the main method:
static String integerFormat(int i) {
DecimalFormat df = new DecimalFormat("$#,###.##");
String s = df.format(i);
return s;
}
The format syntax is fairly simple. Most digits appear exactly as written in the final number format. Pound signs (#) represent optional numbers. For example, if the number given had decimal places, then "#.##" will show decimal places. But, if there are no decimals places, then the decimals would not appear. On the other hand "0" is a required number. If you replaced "#.##" with "#.00," then the two decimal places would always appear, even if the value doesn't have a decimal value.
-
5
Click "Run."
-
1