把一个字符串转成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 stringif (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;}

一遍一遍的……你突然明白自己还活着,

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

相关文章:

你感兴趣的文章:

标签云: