Java 绕线的最佳方法
在同一命令中,将价格四舍五入到小数点后两位的最佳方法是什么。 示例:7.254545至7.25 如果数据显示为字符串Java 绕线的最佳方法,java,android,Java,Android,在同一命令中,将价格四舍五入到小数点后两位的最佳方法是什么。 示例:7.254545至7.25 如果数据显示为字符串 ArrayList<HashMap<String, String>> productsHashMapList; holder._price.setText(productsHashMapList.get(position).get("price")); arraylistproductsShashMapList; holder._price.setTex
ArrayList<HashMap<String, String>> productsHashMapList;
holder._price.setText(productsHashMapList.get(position).get("price"));
arraylistproductsShashMapList;
holder._price.setText(productsHashMapList.get(position.get(“price”));
首先使用
Double yourNumber = Double.parseDouble(yournumberinstring);
然后,要将其限制在小数点后2位,请使用
String.format("%.2f", yourNumber);
哪条消息?抱歉:java.util.IllegalFormatConversionException:f!=java.lang.StringIs
d
是字符串吗?如果是这样,您需要先将其转换为double
。使用double d=double.parseDouble(str)
先将字符串转换为double,然后使用string rounded=string.format(“%.2f”,d)
要将字符串中的double四舍五入到2 dp,为什么这比另一种方法更可取?为什么不通过调用字符串构造函数直接初始化BigDecimal
对象<代码>新的大十进制(“7.254545”)代码>它更可取,因为最接近的是解决方案2,但它不会对数字进行四舍五入。这只会“削减”超过2个小数点的任何内容大小数的官方文件说“注意:对于除float和double NaN和±无穷大以外的值,此构造函数与float.toString(float)和double.toString(double)返回的值兼容”。这通常是将浮点或double转换为BigDecimal的首选方法,因为它不会受到BigDecimal(double)构造函数的不可预测性的影响。”
String.format("%.2f", yourNumber);