字符串數字轉換成對應的Double數值


一,介紹

前面實現了字符串轉換成整形數值。參考這里:

它不支持小數,不支持符號(正、負號)

現在實現一個更復雜一點字符串轉換成數值的程序。

它支持“浮點字符串”轉換成對應的浮點數值,如: "123.45" --> 123.45

支持字符串前面或者后面有空格的情況,如:"  123.45   " --> 123.45

支持帶符號的情況,如:"-123.45" -->  -123.45

 

借助它,也可以實現字符串轉換成整形數值。

 

二,思路

需要考慮的細節:

①字符串前面和后面是否有空格?

②是否有小數點?

總體思路與這篇文章 參考這里:  一樣

但是,它在遇到小數點后,繼續求值,但返回結果時會移N位(除10*N)。

 

輸入:由代表數值的字符串,如 "123.45"

輸出:該字符串表示的數值,如 123.45

不允許這種格式的輸入:"12   3.45"

三,代碼如下:

 1     private static double atof(String operand){
 2         double val, power;
 3         int sign,index = 0;
 4         operand = operand.trim();
 5         char first = operand.charAt(0);
 6         
 7         sign = (first == '-') ? -1 : 1;//判斷符號
 8         if(first == '-' || first == '+')
 9             index = 1;//如果字符串的第一個字符為符號,則從 index=1處開始尋找數字
10         for(val = 0.0; index < operand.length() && isdigit(operand.charAt(index)) ; index++)
11             val = val * 10.0 + (operand.charAt(index) - '0');
12         if(index < operand.length() && operand.charAt(index) == '.')
13             index++;//若有小數點, 跳過小數點尋找數字
14         for(power = 1.0; index < operand.length() && isdigit(operand.charAt(index)); index++)
15         {
16             val = val*10.0 + (operand.charAt(index) - '0');
17             power *= 10.0;//相當於記錄小數點后面的位數
18         }
19         return sign * val / power;
20     }

 

可借助它實現字符串轉換成整數的功能。

1     public static int atoi(String operand){
2         return (int)atof(operand);
3     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM