I am trying to format and save a double using BigDecimal, as I want to use the rounding modes available to it. This code however causes a compilation error:
import java.math.*;
public class Format {
public static void main (String[] args) {
double result = 123.456;
int decimalPlaces = 2;
result = BigDecimal.valueOf(result).setScale(decimalPlaces, RoundingMode.HALF_UP);
System.out.println(result);
}
}
The error encountered:
Format.java:10: error: incompatible types: BigDecimal cannot be converted to double
result = BigDecimal.valueOf(result).setScale(decimalPlaces, RoundingMode.HALF_UP);
The value of result I am looking for is:
123.46
Please help me understand how to correct this.
Edit: I understand that my brevity in asking the question has lead to the question being down voted. It appears as if I encountered a compile error and immediately came to ask for a solution which is not the case. I'll take the time to give clearer exposition next time.
It fails because your variable result
is of type double
, while operations on a BigDecimal will usually produce values of type BigDecimal. You cannot put a BigDecimal in a variable of type double
. You need a variable of type BigDecimal.
Which is what the error message was very clearly telling you, and it is rather concerning that you chose to ignore it and come ask here instead.
The value of result I am looking for is:
123.46
A double
is a rather wrong tool for getting to that. doubles are approximate, and you're telling that you want a very exact result and nothing else than that result. Therefore, not an approximation.
If your only goal is to display 123.46
as a result of the number 123.456 you had and that you round to two decimals, then the key word is display. The right tool for displaying text is a String, not a double.
Use a DecimalFormat.
NumberFormat format = new DecimalFormat("0.00");
String s = format.format(result);
System.out.println(s);
No need for BigDecimal.