问题:
给一个字符串,比如“-12.05”,把它转成相应的double类型的数。
分析:
在进行转换的时候,要注意以下问题:
1. 该字符串是否为空
2. 是否该字符串含有符号;
3. 该字符串内是否有非法字符;
4. 小数点的位置;
5. 该数是否越界;
代码如下:
public static double atod(String str) throws Exception {
boolean negative = false;
//get the value before the "."
double valueBeforeDot = 0.0d;
//get the value after the ".";
double valueAfterDot = 0.0d;
boolean pointAppear = false;
int count = 0;
//null or empty string
if (str == null || str.equals("")) {
throw new Exception("null string or the string has no character!");
}
for (int i = 0; i < str.length(); i++) {
//check whether the first character is "+" or "-"
if (i == 0 && (str.charAt(0) == '-' || str.charAt(0) == '+')) {
if (str.charAt(0) == '-') {
negative = true;
}
} else {
//check whether the character is "." and appears for
//the first time and appears at the correct position.
if (pointAppear == false && i != 0 && str.charAt(i) == '.'
&& (str.charAt(0) != '-' || str.charAt(0) != '+')) {
pointAppear = true;
} else {
if (str.charAt(i) >= '0' && '9' >= str.charAt(i)) {
if (pointAppear == false) {
valueBeforeDot = valueBeforeDot * 10 + (str.charAt(i) - '0');
if (valueBeforeDot > Double.MAX_VALUE) {
throw new Exception("out of Double range");
}
} else {
valueAfterDot = valueAfterDot * 10 + (str.charAt(i) - '0');
count++;
}
} else {
throw new NumberFormatException("not a double");
}
}
}
}
valueBeforeDot = valueBeforeDot + valueAfterDot /Math.pow(10, count);
return negative == true ? valueBeforeDot * -1 : valueBeforeDot;
}
扩展:
把一个字符串转成一个整数。 解答可以参考http://blog.csdn.net/beiyeqingteng/article/details/7000034
转载请注明出处:http://blog.csdn.net/beiyeqingteng