5

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,239
  • 4
  • 28
  • 36
user8610600
  • 63
  • 1
  • 4

2 Answers2

11

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,417
  • 2
  • 12
  • 15
2

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
  • 83
  • 8