AI智能
改变未来

自己实现Double.valueOf()

闲着没事,自己实现了一下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;}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 自己实现Double.valueOf()