|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
How to Format a Number in Java
This examples shows how to format a number. This is often useful if you have either a very large number which will not be formatted well just using the normal System.out. or if you have a number that contains many decimals that you want to reduce to just a few. In this example we format a large number to be readable. In order to do so we use the DecimalFormat class to which we pass the format we want to use (#0.00). The format tells the DecimalFormat to present the number with two decimals. The actual formatting is done by calling the format() method on the DecimalFormat object. Notice the difference when the accountBalance number is printed out before the formatting is done, and then afterwards. |
package com.javadb.examples; import java.text.DecimalFormat; public class Main { public static void main(String[] args) { double accountBalance = 10765880.2048; DecimalFormat formatter = new DecimalFormat("#0.00"); System.out.println(accountBalance); System.out.println(formatter.format(accountBalance)); } } |
| The output from the code above is: |
1.07658802048E7 10765880,20 |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
