How to Format Decimals in Java

How to Format Decimals in Java thumbnail
You can have your Java code generate numerical output in the format of your choice.

Given a non-integer numerical value (that is, a decimal value), the Java programming language allows you to format that value to suit the needs of your particular application. Java displays a given maximum number of decimal places, or of integer places; it can left- or right-justify the formatted number to any number of spaces. Your Java program uses these capabilities to generate neat tables where all numbers are lined up in columns, or to satisfy application-dependent requirements (e.g., dollar amounts formatted to two decimal places representing cents).

Instructions

    • 1

      Include the following line at the beginning of your Java code:

      import java.util.*;

    • 2

      Create an instance of the built-in Formatter class, as in the following sample code:

      Formatter myFormatter = new Formatter();

    • 3

      Format a decimal value into whatever format you need, as in the following sample code:

      float myFloat = 46.30;

      double myDouble = 87.494;

      myFormatter.format("%5.f",myFloat);

      System.out.println(myFormatter);

      myFormatter.format("%-6.2f",myDouble);

      System.out.println(myFormatter);

      The first example will format the "float" (single-precision floating point value) for five places before the decimal period and no decimal places, right-justified; the result will therefore be " 46.", with two spaces before the digit "4". The second example will format the "double" (double-precision floating point value) to a total of six places, of which one is the decimal point and two more are decimal places, all left-justified; the result will therefore be "87.49 " (with one space after the digit "9").

Related Searches:

References

  • Photo Credit Hemera Technologies/AbleStock.com/Getty Images

Comments

Related Ads

Featured