[英]How to Convert String value into Double or Int value in Java?
我有個問題。 我有值為"$615.00"
String
,我想將其轉換為double
或int
。 我嘗試了以下代碼,但出現錯誤:
String one = "$615.00";
String two = "$15.00";
double newone = Double.parseDouble( one );
double newtwo = Double.parseDouble( two );
System.out.println(newone-newtwo);
錯誤是
Exception in thread "main" java.lang.NumberFormatException: For input string: "$615.00"
但是我為該方法添加了NumberFormatException
並且仍然出現錯誤。
正如其他人在評論中所說的那樣,發生 NumberFormatException 是因為您試圖 parseDouble 而不從數字中刪除 $ 。
在這種情況下,您可以使用substring()獲取第一個字符之后的所有內容:
String one = "$615.00";
String two = "$15.00";
double newone = Double.parseDouble( one.substring(1) );
double newtwo = Double.parseDouble( two.substring(1) );
System.out.println(newone-newtwo);
結果在 600.00
$
是貨幣指示符。 它不是數值的一部分。
如果您有貨幣值,則應使用貨幣格式來讀取它:
NumberFormat format = NumberFormat.getCurrencyInstance();
double newone = format.parse(one).doubleValue();
double newtwo = format.parse(two).doubleValue();
如果您沒有在為美國配置的計算機上運行,則可能需要傳遞 Locale,以強制貨幣實例使用美元:
NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
double newone = format.parse(one).doubleValue();
double newtwo = format.parse(two).doubleValue();
使用正則表達式刪除像“$”這樣的符號(換句話說,除了數字和點之外的所有符號)
String one = "$615.03";
String oneValue = one.replaceAll("[^0-9.]", "");
System.out.println(oneValue); // Output is 615.03, which is correctly parsed by parseDobule()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.