File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes NumberFormat help! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "NumberFormat help!" Watch "NumberFormat help!" New topic

NumberFormat help!

Amir JavaGuy

Joined: Oct 13, 2005
Posts: 2

How do I create a method that formats a number based on it's string value ? Lets say I have the number 1027

I want to call my format routine to return ( lets say my locale is set to English US ) 1,027

If I passed 1027.000 to my routine, I want it to return 1,027.000

I have written the following routine to achieve this goal, but for some reason, any number I pass in with trailing zero's get truncated. If I pass in 1027.123, it works fine. If I pass in 1027.000, it returns 1,027 ! Am I missing something basic ?

Here's the snippet :

protected static String embedProperDelim (String s,
int coding) {

java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
Number myNumber = null;

try {
myNumber = nf.parse (s);
} catch (java.text.ParseException e) {
e.printStackTrace ();

String formatted = nf.format(myNumber);

return formatted;


Any help is much appreciated.
Ed Ewing

Joined: Aug 30, 2005
Posts: 29

Amir JavaGuy

Joined: Oct 13, 2005
Posts: 2
Hi Ed,

Thank you for the quick response. This works when I pass in 1027.000

The result is 1027.000 as I wanted

BUT, what about when I pass in 1027 ? Here, I'd like it to be smart enough to pring out 1027
Seb Mathe
Ranch Hand

Joined: Sep 28, 2005
Posts: 225
I think you have to count traling "decimal-zeros" of your original number and append them after formatting.

Or count the decimal digits and format your number with this minimum value.
[ October 14, 2005: Message edited by: Seb Mathe ]

Regards,<br />Seb<br /> <br />SCJP 1.4
Adam Richards
Ranch Hand

Joined: Nov 03, 2005
Posts: 135
If you use a real name as the forum asks you to, you might get more replies!
I agree. Here's the link:
subject: NumberFormat help!
It's not a secret anymore!