This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Numbers formatting  RSS feed

 
Timothy Leong
Ranch Hand
Posts: 55
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys,
I have a double[100][100] value of double numbers. I need to display all numbers in 10 x 10 format on the screen. What should i do to make the numbers evenly spaced out?

i tried using formatter

formatter = new Formatter ();
formatter.format("%f", numi][j]);

but i would like to make all the values distributed evenly no matter how many decimal places they haf.

Thanks alot
 
Paul Santa Maria
Ranch Hand
Posts: 236
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi -

1. First, you need to make sure you have the new Java 5.0 compiler: formatted printing wasn't available in earlier releases.

2. If you do, you're in luck: the formatter permits specifying both width and precision. Here's the Java on-line documentation:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html

I'd suggest writing a 5-line "hello world" to get comfortable with using the Formatter object first. Then write your program to print the 10x10 array afterwards.

'Hope that helps .. PSM
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't know if you can get NumberFormatter to do the job or not.

If not, you can pad the strings to a known length. I made a function right() for rightJustify that pads or truncates to a specified length and lets you specify the pad character or string:

formatted = StringUtil.right( input, 10, " " );

For one-off use, you might make a method that does this:

return (" " + input).substring( input.length() );
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!