aspose file tools*
The moose likes Java in General and the fly likes Formatting numbers with patterns Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Formatting numbers with patterns" Watch "Formatting numbers with patterns" New topic
Author

Formatting numbers with patterns

Mick Techoes
Greenhorn

Joined: Mar 20, 2006
Posts: 3
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

Joined: Sep 20, 2003
Posts: 1704
Look at :
http://java.sun.com/docs/books/tutorial/i18n/format/decimalFormat.html
Mick Techoes
Greenhorn

Joined: Mar 20, 2006
Posts: 3
Allready done. Does not tell anything about spaces inside decimal number.
Kj Reddy
Ranch Hand

Joined: Sep 20, 2003
Posts: 1704
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

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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
 
subject: Formatting numbers with patterns