How to Format a Number in Java

Formatting numbers in Java is used to display values such as currency. Java truncates the "0" values after decimals, so formatting the number displays a standard of two digits after the decimal. For other applications, there may be a need to display numbers with a different format. Luckily, Java comes with an internal function to format numbers with only a few lines of code.

Instructions

    • 1

      Include the format libraries. Class libraries are supplied by the Java compiler for formatting numbers, but they need to be included in the headers of the code. These are the libraries to include in your code:
      import java.text.DecimalFormat;
      import java.text.NumberFormat;

    • 2

      Create the format. Number formats use the "#" symbol. It indicates a number is used in place of the symbol while other characters are statically inserted into the format. The code below is an example of a number format in Java:
      NumberFormat myFormat = new DecimalFormat("#0.00");
      This format will add "0" characters to numbers that are not decimals, similar to what is needed for currency.

    • 3

      Print a formatted number to the display. The following code uses the number format defined in step 2 to format a decimal:
      double myMoney = 88;
      System.out.println(myFormat.format(myMoney));

    • 4

      View the results. If implemented properly, the code should compile and print the following formatted decimal:
      88.00

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured