File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Formatting numbers with patterns

 
Mick Techoes
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I have String containing only numbers and a comma in followin format
nnnnnnnnn,n where n is number 0 - 9.
E.g. the right value would be 121231234,1

I have to convert it into format 12 123 1234,1

How should I code it properly using Java's Formatter classes?
I can code that using loops etc. but I do not want to code such
code. So, anyone know how to do it with formatters. I have to support JDK 1.4.

I tried a code below, but spaces in the last line does not appear between
numbers. I know that might approach can also be wrong.
Could someone please, how handle this formatting nicely.

String s = "121231234,1";
double d = Double.parseDouble(s);

DecimalFormat df = new DecimalFormat("## ### ####.0");

System.out.println(String.format("## ### ####.0", d));


// Output is still 121231234,1 but I would like have
// it in form 12 123 1234,1


Cheers!
 
Kj Reddy
Ranch Hand
Posts: 1704
 
Mick Techoes
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Allready done. Does not tell anything about spaces inside decimal number.
 
Kj Reddy
Ranch Hand
Posts: 1704
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Mick, I too tried but no sucess. How about using String. replace() or replaceAll() methods to convert into required formats instead of using for loops:

for example look at the following sample class
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got close to the desired output by manipulating the DecimaFormatSymbols, but I cant get it to do the variable grouping widths.

[ March 20, 2006: Message edited by: Garrett Rowe ]
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Garrett: ...but I cant get it to do the variable grouping widths

A closer look at the documentation reveals that a DecimaFormat object won't do variable width parsing.

The grouping size is a constant number of digits between the grouping characters, such as 3 for 100,000,000 or 4 for 1,0000,0000. If you supply a pattern with multiple grouping characters, the interval between the last one and the end of the integer is the one that is used. So "#,##,###,####" == "######,####" == "##,####,####".
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic