Line up, everybody! Line up, Line up! Making decimals in Strings to line up in Java

Okay, sorry for the title.  Having kids, I’ve seen Bubble Guppies way too many times.  On to the topic at hand.  I just had a Java project in which I had multiple currency and percent values in the form of Strings that were stacked vertically, but I needed to make the decimal points line up for uniformity’s sake.  Unfortunately, I searched far and wide for a simple solution – some built-in feature that would do this for me – but nothing came up.  So I decided to create my own function that would solve the problem.  NOTE: If you know of an easier way to do this, please let me know as I’m still learning!

First of all, the requirements of my project asked that my numbers be formatted using the NumberFormat class.  For any monetary value, the number would be formatted using the getCurrencyInstance() method, and percentages using getPercentInstance() with setMinimumFractionDigits(3) and setMaximumFractionDigits(3).  Therefore, when I format currency, the result is a string like “$1,000.00″, and percentages show like “5.250%”.

In my application, a Loan Interest Calculator, I needed to print out the principal amount, interest rate, total interest, and total loan repayment amounts.  Obviously you can see my issue with the decimals not lining up.  My first run of the program produced the following output:

Loan Amount:   $1,000.00
Interest Rate: 10.250%
Interest:      $102.50
Repayment:     $1102.50

Note that, in my source code, I’m printing out a concatenation of string literal (i.e. “Loan Amount: “) and a variable (i.e. loanAmount) so that I can format the number properly. Like this:

System.out.println("Loan Amount: " + loanAmount);

Now that you can see the problem, I’ll move on to the solution. In my mind, I needed to add a certain unknown number of spaces before each amount to make the decimals line up. Clear as mud? In my case, I knew that one particular value, the repayment amount, would always be the largest. So my idea was to first find the length of the largest value, then find the difference between that and value I wanted to format. Then, using a for loop, I would create a String of spaces equal to the difference in length. Here’s the beginning of my function:

private static String formatForDecimals(String number, String largest) {
    int totalPrefix = largest.length() - number.length();
    String prefix = "";
    String formattedNum = "";
    for (int i = 0; i < totalPrefix; i++) {
        prefix += " ";
    }
    formattedNum = prefix + number;
}

To test this, I simply called the formatForDecimals() method in my println for each value, like this:

System.out.println("Loan Amount: " + formatForDecimals(loanAmount, repayment));

This got me really close, as you can see:

Loan Amount:  $1,000.00
Interest Rate:  10.250%
Interest:       $102.50
Repayment:     $1102.50

The one thing I didn’t account for was the extra decimal place and percent sign in the percentage. So i tweaked my function with this:

private static String formatForDecimals(String number, String largest) {
    int totalPrefix = largest.length() - number.length();
    if (number.contains(%)) {
        totalPrefix += 2;
    }
    String prefix = "";
    String formattedNum = "";
    for (int i = 0; i < totalPrefix; i++) {
        prefix += " ";
    }
    formattedNum = prefix + number;
}

Basically, I wanted to check the String to see if it was a percentage and, if so, add two extra spaces to account for the extra characters. And it worked! I got the following output:

Loan Amount:  $1,000.00
Interest Rate:    10.250%
Interest:       $102.50
Repayment:     $1102.50

Okay, so I know this is not a perfect solution by any means. As I said, I’m not a Java expert, so if you know of anything that would’ve made this easier, post a comment or something! I’m always welcome to learning new things.

Oh, and just for clarification, the reason I included the “largest” as a parameter was because I had to use the same formatting in a different place with different values, so I wanted to make my code reusable.

Thanks for reading!
Chris

About these ads

One response to “Line up, everybody! Line up, Line up! Making decimals in Strings to line up in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s