Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert BigDecimal to float having 2 decimal in java [duplicate]

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.

like image 849
user8610600 Avatar asked Sep 21 '17 18:09

user8610600


People also ask

How do you create a float with 2 decimals in Java?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you convert a large decimal to a float?

BigDecimal. floatValue() converts this BigDecimal to a float. If this BigDecimal has too great a magnitude represent as a float, it will be converted to Float.


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"
like image 195
Vladimír Bielený Avatar answered Oct 22 '22 18:10

Vladimír Bielený


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

like image 24
Varun Avatar answered Oct 22 '22 18:10

Varun