How to convert BigDecimal to float having 2 decimal in java

Viewed 10181

How can I convert a BigDecimal to float, having 2 decimal in java?

BigDecimal x=new BigDecimal(any exponential term);

Now I want to convert to float having 2 decimal point only, for example -0.45.

2 Answers

You can use setScale to round number to any given decimal places.

BigDecimal number = new BigDecimal(2.36359);
float rounded = number.setScale(2, RoundingMode.DOWN).floatValue();
System.out.println(rounded);    // prints "2.36"

Once you have the BigDecimal. Use x.floatValue() to compute float and then pass it through Math.round() to round it to 2 digits.

Related