把一个字符串转成double类型的数[# 61]
来源:互联网 发布:java输入多行字符串 编辑:程序博客网 时间:2024/06/05 20:41
问题:
给一个字符串,比如“-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 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;}} 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
- 把一个字符串转成double类型的数[# 61]
- 把一个字符串转成double类型的数
- 把一个字符串转成double类型的数
- javascript把字符串转成double
- 把字符串转成number类型
- java 中把double类型转成 int类型
- SQL, 先把字符串转成date类型.. 然后做月的加减. 做完再把date类型转成varchar类型...
- 一个把中文字符串转成拼音串的函数
- 把一个字符串的首字母转成大写,其余为小写。(
- gcvt 把浮点数转成字符串
- 把字符串数字转成uint64_t类型
- 关于如何把带有千分符浮点数字符串转换成double类型
- 求图像的均值(重点把uint8转成double)
- 把对象转成字符串
- 在java中,怎样把一个double数转换为字符串时,不用科学计数法表示。
- 在java中,怎样把一个double数转换为字符串时,不用科学计数法表示。
- 把一个任意数转成radix进制数,radix(1-36)
- [C/C++] 把一个整型整数转成字符串
- poi 机制 效率最高的 excel 导入Oracle (源码)
- 内存数据库(TimesTen)cachegroup配置指南
- VisualSVN server和TortoiseSVN的使用方法
- 你一定要幸福 13
- 你一定要幸福 14
- 把一个字符串转成double类型的数[# 61]
- 获取邮箱用户名
- STL中erase()小心使用
- Android应用开发之(你必须知道的“避免内存溢出图片处理方案”)
- 百度向业界分享海量数据处理技术
- hdu2094
- C++复习九 冒泡排序法
- jQuery UI全教程之一(dialog的使用教程)
- java.lang.IllegalArgumentException: node to traverse cannot be null!