我有一个价格为 70,00 的字符串 另一个字符串的价格为 25,00
我想将它们相加(求和),并且我得出结论 r=我必须使用 BigDecimal 来完成它。
这是我的代码:
String CPUprice = "70,00"
String CPU_COOLERprice = "25,00";
BigDecimal price1 = new BigDecimal(CPUprice);
BigDecimal price2 = new BigDecimal(CPU_COOLERprice);
BigDecimal price_final = price1.add(price2);
TextView finalPrice = (TextView) findViewById(R.id.final_price); // Find TextView with Final Price
finalPrice.setText(NumberFormat.getCurrencyInstance().format(price_final)); // Set Final Price TextView with The Final Price
但是,它给出了错误
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.kayioulis.pcbuilder/com.kayioulis.pcbuilder.MainActivity}: java.lang.NumberFormatException: Invalid long: "0,00"
问题是我使用了逗号 (,)。我使用它是因为我想以欧元显示价格,而欧元的小数位使用逗号 (,)。示例:10,00 欧元 = 10 欧元
如何将两个价格相加?
最佳答案
您应该使用CurrencyFormat 来处理此类特定于区域设置的问题。在进行算术运算之前将它们转换为小数。
CurrencyFormat 似乎存在欧元问题。
package money;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
/**
* CurrencyFormatTest
* @author Michael
* @link https://stackoverflow.com/questions/31524467/calculate-euro-prices-using-bigdecimal/31524497?noredirect=1#comment51014843_31524497
* @since 7/20/2015 7:15 PM
*/
public class CurrencyFormatTest {
public static void main(String[] args) {
String CPUprice = "70,00";
String CPU_COOLERprice = "25,00";
System.out.println(String.format("CPU price: " + convertCurrencyToDouble(CPUprice, Locale.GERMAN)));
System.out.println(String.format("CPU cooler price: " + convertCurrencyToDouble(CPU_COOLERprice, Locale.GERMAN)));
}
public static double convertCurrencyToDouble(String s, Locale locale) {
double value = 0.0;
if ((s != null) && (s.trim().length() > 0)) {
try {
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);
value = currencyFormat.parse(s).doubleValue();
} catch (ParseException e) {
e.printStackTrace();
value = 0.0;
}
}
return value;
}
}
关于java - 使用 BigDecimal 计算欧元价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31524467/