6

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.

Assafs
  • 3,257
  • 4
  • 26
  • 39
user8610600
  • 73
  • 1
  • 1
  • 4

2 Answers2

12

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"
Vladimír Bielený
  • 2,795
  • 2
  • 11
  • 16
3

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

Varun
  • 113
  • 1
  • 8