圆弦的最佳方法[关闭]

问题描述 投票:2回答:2

在同一个命令中将价格四舍五入到2位小数的最佳方法是什么。例如:7.254545到7.25如果数据显示为字符串?

ArrayList<HashMap<String, String>> productsHashMapList;
holder._price.setText(productsHashMapList.get(position).get("price"));
  1. 使用拆分?在(。)之后的2个数字后拆分?
  2. 使用(.format(“%。2f”,d))。
  3. 使用xml TextView(IF POSSIBLE)?

为什么?并请给我一些信息,因为第二种方式不起作用,并显示此消息:java.util.IllegalFormatConversionException:f!= java.lang.String

java android
2个回答
1
投票

首先将您的字符串转换为double使用

Double yourNumber = Double.parseDouble(yournumberinstring);

然后将其限制为2位小数使用

String.format("%.2f", yourNumber);

-1
投票

你去(这将围绕数字):

double val = Double.parseDouble(productsHashMapList.get(position).get("price"));
BigDecimal bd = new BigDecimal(val);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);
holder._price.setText(""+bd.floatValue());
© www.soinside.com 2019 - 2024. All rights reserved.