Howdy, Stranger!

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

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

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.