如何将百分比字符串转换为BigDecimal?

15

在Java中,如何将百分比字符串转换为BigDecimal?

谢谢

String percentage = "10%";
BigDecimal d ; // I want to get 0.1 

似乎是重复的问题:https://dev59.com/anI95IYBdhLWcg3w3yJU - Mohamed Saligh
4个回答

15
尝试使用 new DecimalFormat("0.0#%").parse(percentage)

Namal在这里提供了一行代码的答案,而不是再次进行除法。很好。 - Ruchira Kariyawasam
3
请记住,这种方法不能用于像“10.5%”这样的内容。 - Rasmus Faber
2
@RasmusFaber 它将会 - maksimov
DecimalFormat 的内部计算存在精度损失!new DecimalFormat("0.0#%").parse("0.9%") -> 0.009000000000000001 - Luzifer42

4
BigDecimal d = new BigDecimal(percentage.trim().replace("%", "")).divide(BigDecimal.valueOf(100));

1
    DecimalFormat f = new DecimalFormat("0%");
    f.setParseBigDecimal(true);// change to BigDecimal & avoid precision loss due to Double
    BigDecimal d = (BigDecimal) f.parse("0.9%");

使用DecimalFormat的优点是避免了脆弱的字符串操作,而且还可以根据本地化设置解析数字(小数分隔符、分组分隔符、减号等)。如果您不知道格式或不想硬编码它,则还可以使用NumberFormat.getPercentInstance()。

1
只要你知道在你的字符串末尾始终有百分号符号(%),就可以了解。
BigDecimal d = new BigDecimal(percentage.substring(0, percentage.length()-1));
d.divide(100); // '%' means 'per hundred', so divide by 100

如果你不知道 % 符号会出现在那里:

percentage = percentage.replaceAll("%", ""); // Check for the '%' symbol and delete it.

BigDecimal d = new BigDecimal(percentage.substring(0, percentage.length()-1));
d.divide(new BigDecimal(100));

1
BigDecimal类中没有divide(int)方法。 - Eng.Fouad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接