把一个字符串转成double类型的数[# 61]

问题:

给一个字符串,比如“-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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值