• Post Reply Bookmark Topic Watch Topic
  • New Topic

Number Formatting  RSS feed

 
Charith Jayasinghe
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need this to be done in a form printing code.

I have an int variable, which may contain a decimal value. I need to convert it to a standarc format. For an example, say my value is 148.05, the code should format it as ####148.05

if the value is 4589.00, then the outcome must be ###4589.00

the length of the var is constant. Can any one give me a logic please.
 
Scott Selikoff
author
Bartender
Posts: 4093
21
Eclipse IDE Flex Google Web Toolkit
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well some moderator is going to say something since this post is also posted at:

http://www.coderanch.com/t/401397/java/java/Number-Format

but to answer your question...

First off, how do you have an int variable that stores a decimal? This is, by construction, a contradiction, so you lost me all ready. Second, there's a whole API for formatting numbers called java.text.NumberFormat, which includes as a subclass, java.text.DecimalFormat. Read the API at:

http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html

You create a formatter object with the desired output format, then send in your input using format() to produce a string output. Its pretty easy to use.
 
Charith Jayasinghe
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mistakenly i have mentioned it as DECIMAL. Sorry abt that.

I am trying to solve my matter with the help of URL given. I'll update the progress.

THANKS!
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Charith Jayasinghe:
I am trying to solve my matter with the help of URL given. I'll update the progress.


Just don't start yet another thread to do that!
 
Charith Jayasinghe
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry!
 
Charith Jayasinghe
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
----------------------------------------------------
//Using Strings <too simple to ask this question>

public String numberFormatter(String Amt)
{
while (Amt.length()!=11)
{
Amt = "#"+Amt;
}
return Amt;
}

------------------------------------------------------

//Using a char[]

public String numberFormatter(String Amt)
{
char [] ca = new char[Amt.length()];
Amt.getChars(0, Amt.length(), ca, 0);
char[] fa = new char[11];
int y=ca.length-1;
for(int x=11; x>fa.length-ca.length; x--)
{
fa[x-1]=ca[y];
y--;
}

for(int x=0; x<fa.length;x++)
{
if(fa[x]=='\u0000')
fa[x]='#';
}
return new String(fa);
}
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!