JAVATM- The Beginnings

Formatting Output

Suppose you wrote a program which stores a monetary amount as the number of cents.

The program then splits the amount into dollars and cents, then prints a formatted string displaying them.

        int money = 501;

        int dollars = money / 100;

        int cents = money % 100;

        System.out.println("$" + dollars + "." + cents);        // Prints $5.1

The example above computes the value one for the number of cents, then displays it immediately after the decimal point, which implies that the amount is five dollars and ten cents instead of five dollars and one cent. Fortunately, Java provides several ways to display this output in a more readable fashion.

Section 1 - The NumberFormat Class

The NumberFormat class provides several objects which can be used to format numbers. The format method of each object is called to return a formatted string. The NumberFormat class is part of the java.text package.

Section 1a - The getNumberInstance Method

The static getNumberInstance method returns a formatter that works on raw numbers. Any of the following modifiers can be called to change how the number is formatted.

void setMinimumIntegerDigits(int m)

Sets the minimum number of digits displayed in the integer portion of a number.

void setMaximumIntegerDigits(int m)

Sets the maximum number of digits displayed in the fractional portion of a number.

void setMinimumFractionDigits(int m)

Sets the minimum number of digits displayed

Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.

Back to