现在的位置: 首页 > 综合 > 正文

字符串转换的类,如230991.291==>230,991.291

2013年03月25日 ⁄ 综合 ⁄ 共 1813字 ⁄ 字号 评论关闭

public class FloattoString{

//if given 230991.291, should return the String "230,991.291"
//if given 200.0, should return the string "200"
//if given 87238.001, should return the string "87,238.001"
//if give -23870.0, should return the string "-23,870"

public String doubleToString(double value){
 String strValue=value+"";
 String strInt="";//取其整形部分
 String strDec="";//取其小数部分
 String result="";
 //检查是否有小数点
 int pos=strValue.lastIndexOf(".");
 //if(pos>0){
  //把字符按小数点拆分

  strInt=strValue.substring(0, pos);
  strDec=strValue.substring(pos);

  int intValue=Integer.parseInt(strInt);
  //加上小数部分
  if(intValue!=value){
   result+=strDec;
  }

  //如果是正数则直接输出,负数则加上负号
  String resultTemp="";
  if(intValue>=0){
   resultTemp=getResult(intValue);
   result=resultTemp+result;
  }else{
   intValue=intValue*-1;
   resultTemp=getResult(intValue);
   result="-"+resultTemp+result;
  }
  //如果小数点后为0则不按整数输出
 //}
 return result;

 }
 //把传过来的整弄值变成123456789--->123,456,789
 private String getResult(int value){
  int intValue=value;
  String result="";
  while(true){
   int t1=intValue/1000;
   int t2=intValue%1000;
   if(t1!=0){
    result=","+t2+result;
   }
   //最后一次前面不加","
   if(t1==0){
    result=t2+result;
    break;
   }
   intValue=t1;
  }
  return result;
 }
public static void main(String[] args){
 //if given 230991.291, should return the String "230,991.291"
 //if given 200.0, should return the string "200"
 //if given 87238.001, should return the string "87,238.001"
 //if give -23870.0, should return the string "-23,870"
 double a=(double)230991.291;
 double b=(double)200.0;
 double c=(double)87238.001;
 double d=(double)-23870.0;
 double e=(double)1234567;
 FloattoString fs=new FloattoString();
 String rs=fs.doubleToString(a);
 System.out.println(rs);
 System.out.println(fs.doubleToString(b));
 System.out.println(fs.doubleToString(c));
 System.out.println(fs.doubleToString(d));
 System.out.println(fs.doubleToString(e));
 //System.out.println(123.0==123);
}

}

抱歉!评论已关闭.