user595234
user595234

Reputation: 6259

how to convert percentage String to BigDecimal?

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

Answers (4)

Luzifer42
Luzifer42

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

namalfernandolk
namalfernandolk

Reputation: 9134

Try new DecimalFormat("0.0#%").parse(percentage)

Upvotes: 15

Eng.Fouad
Eng.Fouad

Reputation: 117627

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

Upvotes: 4

Jon Egeland
Jon Egeland

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

Related Questions