我使用:
priceTextView.setText(String.format("%.2f",price));
价格翻倍。它有效,但是当我必须从 TextView 检索值并将其转换为 double 时,出现以下错误:
java.lang.NumberFormatException: Invalid double: "1,2"
是否有另一种方法可以做同样的事情并避免错误?
完整代码如下:
Double prezzoDouble = Double.parseDouble(this.prezzo);
prezzoTextView.setText(String.format("%.2f", prezzoDouble));
quantitaSceltaEditText.addTextChangedListener(new TextWatcher() {
String prezzoUnitario=prezzo;
public void afterTextChanged(Editable s) {
int quantitaSceltaInt = Integer.parseInt(quantitaSceltaEditText.getText().toString());
if(quantitaSceltaInt>=1) {
String prezzoTotale = String.valueOf(String.format ("%.2f", (calcoloPrezzoTotale())));
prezzoTextView.setText(prezzoTotale);
}
else
{
prezzoTextView.setText(prezzoUnitario);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
private double calcoloPrezzoTotale()
{
double prezzoNum=Double.parseDouble(prezzoTextView.getText().toString()); ///////////
double prezzoTotale=0;
int quantitaSceltaNum = Integer.parseInt(quantitaSceltaEditText.getText().toString());
prezzoTotale = prezzoNum * quantitaSceltaNum;
return prezzoTotale;
}
});
最佳答案
看起来像行中的双重赋值
prezzoTotale = String.valueOf(String.format ("%.2f", (calcoloPrezzoTotale())));
由于区域设置,包含逗号(,
,即 1,2
)。因此,请注意使用相同的语言环境进行解析。
类 NumberFormat
帮助你:
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();
查看您的代码,它也可能是 Locale.ITALY
;) 检查完整的 Locale 列表 here .
p.s.:String.format()
根据 documentation 使用 Locale.getDefault();
.使用 logcat 检查它的值,如果您不确定系统设置或使用替代方法 public static String format(Locale l, String format, Object... args)
允许您指定语言环境。
关于java - 使用 double 仅显示小数点后两位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29637005/