Reputation: 6259
In java, how to convert percentage String to BigDecimal ?
Thanks
String percentage = "10%";
BigDecimal d ; // I want to get 0.1
Upvotes: 15
Views: 16910
Reputation: 708
DecimalFormat f = new DecimalFormat("0%");
f.setParseBigDecimal(true);// change to BigDecimal & avoid precision loss due to Double
BigDecimal d = (BigDecimal) f.parse("0.9%");
Using DecimalFormat has the advantage that you avoid fragile String manipulations and you can even parse numbers according to your locale (DecimalSeparator, GroupingSeparator, minusSign, ...).
You could also use NumberFormat.getPercentInstance()
if you don't know the format or don't want to hardcode the it.
Upvotes: 1
Reputation: 117627
BigDecimal d = new BigDecimal(percentage.trim().replace("%", "")).divide(BigDecimal.valueOf(100));
Upvotes: 4
Reputation: 12623
As long as you know that the %
symbol will always be at the end of your String
:
BigDecimal d = new BigDecimal(percentage.substring(0, percentage.length()-1));
d.divide(100); // '%' means 'per hundred', so divide by 100
If you don't know that the %
symbol will be there:
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));
Upvotes: 1