Number Format

Charith Jayasinghe
Greenhorn
Posts: 23
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.

Campbell Ritchie
Sheriff
Posts: 50277
80
Have you looked up the java.util.Formatter class in API? It has a whole list of formatting options with % signs in. They are used alike in Formatter, in java.lang.String.format() and in [java.lang.System.out].printf().

It is a bit difficult to work out from your question what exactly you want. You say you have two int variables which are the same length and then quote two floating point numbers which are different lengths. You can't have a decimal point in an int variable.

CR

Charith Jayasinghe
Greenhorn
Posts: 23
Ya i have made a mistake by saying an int variable. Anyway again the question is this :

When people printing amounts in bills and cheques, they use a standard format to avoid frauds. For an example amount will always display in a fixed number of didgits, assume its 10 digits for a while. So, if the amount to be printed is \$ 4501.00, then it should be printed as \$ ###4501.00

There will be fixed number of digits. And does anybody has a good algorythm to convert numbers in to words ?

marc weber
Sheriff
Posts: 11343
If I'm understanding this, you have a double value d, and you want to display it with a total of x characters to the left of the decimal, using the '#' character to pad any leading space.

There are a variety of ways to approach this. Here's the basis for one algorithm: Starting at the left, if d / 10^(x-1) is less than 1, then you want a '#'...

Or for an easier approach, use the length() method of the String class to determine how many '#' chars you need.

Charith Jayasinghe
Greenhorn
Posts: 23
Thanks for the guidance!

Charith Jayasinghe
Greenhorn
Posts: 23
----------------------------------------------------
//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);
}
--------------------