2016-01-19 26 views
4

有一個內置在Java例程,將百分比轉換爲數字,例如,如果字符串包含100%或100像素或100,我想含有浮標100Java的「100%」,以數

使用Float.parseInt或Float.valueOf會導致異常。我可以編寫一個例程來解析字符串並返回數字,但我問這是否已經存在?

+0

乘以結果這對你有意思的http:// stackoverflow.com/a/9714333/563732 – xitx

回答

0

謝謝你的職位和建議,我也嘗試使用張貼eg04lt3r的解決方案,但是結果被翻譯。最後我寫了一個簡單的函數,它完全符合我的要求。我相信一個好的正則表達式也會起作用。

public static double string2double(String strValue) { 
     double dblValue = 0; 
     if (strValue != null) { 
      String strResult = ""; 
      for(int c=0; c<strValue.length(); c++) { 
       char chr = strValue.charAt(c); 

       if (!(chr >= '0' && chr <= '9' 
        || (c == 0 && (chr == '-' || chr == '+')) 
        || (c > 0 && chr == '.'))) { 
        break; 
       } 
       strResult += chr; 
      } 
      dblValue = Double.parseDouble(strResult); 
     } 
     return dblValue; 
    } 
+1

爲什麼不使用@ eg04lt3r的答案並乘以100?它會爲你節省很多代碼,看起來更優雅。 –

+0

因爲該代碼僅在轉換值以%結尾時才起作用,而且我需要一種通用方法,該方法適用於可以以%,px或全部結束的字符串。 – SPlatten

+1

您應該更新問題以包含您在此解釋的詳細信息。目前這個問題要求解析字符串「100%」。聽起來你的情況比這更復雜。 –

1

使用StringBuffer刪除%標誌,然後您可以將其轉換。

if (percent.endsWith("%")) { 
    String number = new StringBuffer(percent).deleteCharAt(percent.length() - 1); 
    float f = Float.valueOf(number); 
} else [Exception handling] 

上面的方法更好,但我想我會修復關於評論的答案。在刪除角色之前,你必須確保你處理的是百分比。

+6

這肯定會起作用,但是這個邊界就是黑客行爲,因爲它假定'%'後面沒有字符。在'%'後面添加任何字符都會破壞這種方法。 – dasblinkenlight

18

我認爲你可以使用:

NumberFormat defaultFormat = NumberFormat.getPercentInstance() 
Number value = defaultFormat.parse("100%"); 
+2

這將返回1而不是100 ... – brso05

+1

是的,我嘗試了50%,它返回0.5 – SPlatten

+2

@ brso05這是關於投票系統的好處。它還顯示有多少用戶不關心答案的有效性,只要看起來不錯。 – Tom

0

您對this answer評論表示您需要支持的「%」,「PX」,或者什麼都沒有結束的字符串。如果字符串的唯一內容就是數字和單位,比你應該能夠逃脫:

float floatValue = new DecimalFormat("0.0").parse(stringInput).floatValue(); 

如果您的號碼被其他jibberish包圍字符串的內部,你只希望第一發生這種情況,比你可以利用數ParsePosition

String stringInput = "Some jibberish 100px more jibberish."; 

int i = 0; 
while (!Character.isDigit(stringInput.charAt(i))) i++; 

float floatValue = new DecimalFormat("0.0").parse(stringInput, new ParsePosition(i)).floatValue(); 

這兩種解決方案會給你浮點值,而不需要您通過100