如何将double类型转换为保留两位小数?调用String.format时应用崩溃求助
解决办法:格式化保留两位小数时应用崩溃的问题
嘿,我一眼就找到你崩溃的原因啦!你调用String.format("%.2f", maltRequiredString)的时候犯了个小错误:%.2f这个格式符是专门用来格式化数值类型(比如double或者float)的,但你传入的maltRequiredString是个String对象,类型不匹配直接触发了IllegalFormatConversionException,导致应用崩溃。
正确的做法
直接用计算得到的double类型变量maltRequired来做格式化就好,不用先转成字符串再折腾,代码修改如下:
public void calculate(View view) { String batchVolString = batchVolEditText.getText().toString(); String ogString = ogEditText.getText().toString(); String bheString = bheEditText.getText().toString(); double batchVolDouble = Double.parseDouble(batchVolString); double ogDouble = Double.parseDouble(ogString); double bheDouble = Double.parseDouble(bheString); double specificGravity = 0.96; double maltRequired = (batchVolDouble * ogDouble * specificGravity) / bheDouble; // 直接对double类型的maltRequired做格式化,保留两位小数 String formattedMalt = String.format("%.2f", maltRequired); maltRequiredTextView.setText(formattedMalt + "kg"); }
额外的小建议
另外,你当前的代码没有处理用户输入无效内容的情况(比如输入空字符串、字母或者非数字字符),这也会导致NumberFormatException崩溃。可以加个异常捕获来优化体验:
public void calculate(View view) { String batchVolString = batchVolEditText.getText().toString(); String ogString = ogEditText.getText().toString(); String bheString = bheEditText.getText().toString(); try { double batchVolDouble = Double.parseDouble(batchVolString); double ogDouble = Double.parseDouble(ogString); double bheDouble = Double.parseDouble(bheString); double specificGravity = 0.96; double maltRequired = (batchVolDouble * ogDouble * specificGravity) / bheDouble; String formattedMalt = String.format("%.2f", maltRequired); maltRequiredTextView.setText(formattedMalt + "kg"); } catch (NumberFormatException e) { // 提示用户输入有效的数值 maltRequiredTextView.setText("请输入有效的数字!"); } }
这样不仅解决了保留两位小数的问题,还让你的代码更健壮哦!
内容的提问来源于stack exchange,提问作者gnrcs
相关产品推荐
相关产品推荐

