how to align decimal points? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

how to align decimal points?

klyptaklypta Posts: 1Member
Does anyone know how to align decimal points in a table in a console application? We havent learned the swing/gui stuff yet in Java but i want to make my output look nice anyway.
[code]
for example $500.00
$0.00

should look like this $500.00
$ 0.00
[/code]
Thx for any suggestion you may have

Comments

  • kreitlerkreitler Posts: 218Member
    Hi Klypta,
    I don't know that there's any easy way to align the decimals in a console app. However, you can always do it "by hand".

    Roughly, the algorithm would look like this:

    [code]
    Vector myTable = new Vector();
    ...
    // Fill in the table.
    ...

    // Find the number with the most digits left of the decimal.
    int maxLeftSideDigits = -1;
    for (int i=0; i maxLeftSideDigits)
    maxLeftSideDigits = decimalPos;
    }

    // Now print out the table, padding entries with spaces to align them.
    for (int i=0; i<myTable.size(); i++)
    {
    String record = (String)myTable.elementAt(i);
    int decimalPos = record.indexOf('.');
    while (decimalPos < maxLeftSideDigits) {
    record = " " + record;
    decimalPos++;
    }

    System.out.println(record);
    }

    [/code]

    This might not be exactly correct, but I think it's close. Also, it might have strange side effects if you run it on a list of numbers with no decimal places (though I think it handles that correctly, too).

    I hope this helps.

    Kreitler

    : Does anyone know how to align decimal points in a table in a console application? We havent learned the swing/gui stuff yet in Java but i want to make my output look nice anyway.
    : [code]
    : for example $500.00
    : $0.00
    :
    : should look like this $500.00
    : $ 0.00
    : [/code]
    : Thx for any suggestion you may have
    :

Sign In or Register to comment.