自己实现了一下Double.valueOf(),会存在精度缺失问题。
/**
* 字符串转double
* @param source
* @return
*/
public static double parseDoubleValue(String source){
if(source==null){
throw new NullPointerException(source);
}
source=source.trim();
int length=source.length();
if(length==0){
throw new NumberFormatException("empty String");
}
int index=0;
boolean flag=false;
char ch=source.charAt(0);
//判断首个字符是不是+/-
if(ch<48&&ch!=46){
if(ch=='-'){
flag=true;
}else if(ch!='+'){
throw new NumberFormatException("For input string: \"" + source + "\"");
}
index++;
}
//找到小数点的索引,有可能有多个
int pointCount=0,pointIndex=0;
for(int i=index;i<length;i++){
char character=source.charAt(i);
//判断是不是数字
if((character<48&&character!='.')||character>57){
throw new NumberFormatException("For input string: \"" + source + "\"");
}
if(character=='.'){
pointIndex=i;
pointCount++;
}
}
//存在多个小数点
if(pointCount>1){
throw new NumberFormatException("multiple points");
}
//没有小数点
if(pointCount==0){
pointIndex=length;
}
double result=0;
//遍历小数点之前
for(int i=index;i<pointIndex;i++){
char character=source.charAt(i);
result+=(character-48)*Math.pow(10,pointIndex-i-1);
}
//遍历小数点之后
for(int i=pointIndex+1;i<length;i++){
char character=source.charAt(i);
result+=(character-48)*Math.pow(0.1,i-pointIndex);
}
return flag?-result:result;
}