Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
New Developer
jedrob
Posts: 2
Registered: ‎07-14-2009
My Device: Not Specified
Accepted Solution

String formatting

Hello all,

 

I'm trying to figure out a way to format a string so that I can have an item description and a value line up in a list like what I have below.  This may have been answered before somewhere else, but I haven't been able to find anything yet.  I've tried the method found at http://www.java-forums.org/java-lang/7145-how-display-numbers-leading-zeros.html and didn't find it very effective.  Is there any other method that someone has found to work? 

 

item1       $    5.64

item2       $  12.00

item3       $256.23

 

I've also heard someone recommend a MessageFormat object for this.  I've played with it a little bit, but I'm kind of at a wall with trying to figure out how to set up the format string.  Any help with this would be very appreciated.

 

Thanks

Please use plain text.
Developer
Ted_Hopp
Posts: 1,305
Registered: ‎01-21-2009
My Device: Not Specified

Re: String formatting

The kind of alignment you show in the example isn't something you can accomplish with string formatting if you are using a proportional font to display the results.

 

If you use a fixed font, you can do it with spaces. Unfortunately, MessageFormat doesn't provide all the tools, because (I think) there's no way to specify the width of a format field. The best you can do is something like this:

 

/** * Format a row in the table. The name will be * left justified in its column and the price with * be formatted as currency and right justified * in its column, with the currency sign in the * leftmost position of the column. * * @param name the item name * @param price the item price * @param widths the widths of the columns */ static String formatRow(String name, double price, int []widths) { StringBuffer sb = new StringBuffer(name); int pad = widths[0] - name.length(); while (pad-- > 0) { sb.append(' '); } sb.append('$'); String currency = MessageFormat.format( "{0,number,.00}", new Object[] {new Double(price)}); pad = widths[1] - currency.length() - 1; // for '$' while (pad-- > 0) { sb.append(' '); } sb.append(currency); return sb.toString(); }

 

If you want to use a proportional font and are rendering using a Graphics, you will need to measure the text advance (using Font.getAdvance) of the different parts of each row and compute where each piece of each row should go. One subtlety is that you will want to align the numbers on the decimal point, not right aligned. It might even be easiest to format the whole dollar and cent parts separately.

 




Solved? click "Accept as solution". Helpful? give kudos by clicking on the star.
Please use plain text.