Useful Method to Format Decimals (BETA)

Write here if you have problems with your Java source code

Moderator: Board moderators

Post Reply
randomtaiwanese
New poster
Posts: 32
Joined: Fri Oct 01, 2004 10:53 pm

Useful Method to Format Decimals (BETA)

Post by randomtaiwanese »

Try it, it formats a double to a certain decimal place you want

method description:
FormatDecimal(String in, int dec)
in = input, must be a double into a string
dec = number of decimal places

FormatDecimal(Double inp, int dec)
inp = input, must be a double
dec = number of decimal places

[java]import java.io.IOException;
import java.util.StringTokenizer;
import java.text.NumberFormat;

class Main
{
static String ReadLn(int maxLg)
{
byte lin[]=new byte[maxLg];
int lg=0,car=-1;
try
{
while(lg<maxLg)
{
car=System.in.read();
if ((car<0)||(car=='\n'))
break;
lin[lg++]+=car;
}
}
catch(IOException e)
{
return(null);
}
if ((car<0)&&(lg==0))
return(null);
return (new String (lin, 0, lg));
}
public static void main(String[] args)
{
Main newMain = new Main();
newMain.start();
}
void start()
{
String input;
StringTokenizer tokenizer;
while ((input=Main.ReadLn(255))!=null)
{
tokenizer = new StringTokenizer(input);
//System.out.println(FormatDecimal(new Double(tokenizer.nextToken()).doubleValue(),5));
System.out.println(FormatDecimal(tokenizer.nextToken(),5));
}
}
String FormatDecimal(String in,int dec)
{
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
nf.setMaximumFractionDigits(dec);
in = nf.format(new Double(in).doubleValue());
int k=0;
if(in.charAt(0)=='.')
in = "0"+in;
while((in.charAt(k)!='.')&&!(k>=in.length()-1))
{
if(k<in.length())
{
if(in.charAt(k)=='.')
break;
else k++;
}
else break;
}
int diff = in.length()-k-1;
if(in.charAt(k)!='.')
{
in+=".";
for(int i=0;i<dec;i++) in+="0";
}
else if(dec>diff)
for(int i=0;i<(dec-diff);i++)
in+="0";
return in;
}
String FormatDecimal(double inp,int dec)
{
String in = new String(new Double(inp).toString());
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
nf.setMaximumFractionDigits(dec);
in = nf.format(new Double(in).doubleValue());
int k=0;
if(in.charAt(0)=='.')
in = "0"+in;
while((in.charAt(k)!='.')&&!(k>=in.length()-1))
{
if(k<in.length())
{
if(in.charAt(k)=='.')
break;
else k++;
}
else break;
}
int diff = in.length()-k-1;
if(in.charAt(k)!='.')
{
in+=".";
for(int i=0;i<dec;i++) in+="0";
}
else if(dec>diff)
for(int i=0;i<(dec-diff);i++)
in+="0";
return in;
}
}[/java]
Post Reply

Return to “Java”