把一个字符串转成double类型的数

问题:

给一个字符串,比如“-12.05”,把它转成相应的double类型的数。

分析:

在进行转换的时候,要注意以下问题:

1. 该字符串是否为空

2. 是否该字符串含有符号;

3. 该字符串内是否有非法字符;

4. 小数点的位置;

备注:本文不考虑溢出的情况。

代码如下:

/*
	 * allowed format: -.4; +.4; -1.2; 2.5;35.;+35. 
	 */
	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;
					continue;
				}
			}
			//check whether the character is "." and appears for 
			//the first time and appears at the correct position.
			if (pointAppear == false && str.charAt(i) == '.') {
				pointAppear = true;
				continue;
			} 
			if (str.charAt(i) >= '0' && '9' >= str.charAt(i)) {
				if (pointAppear == false) {
					valueBeforeDot = valueBeforeDot * 10 + (str.charAt(i) - '0');
				} 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; 			
	}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值