I am working on a project that implements base costs of shipping fees and whatnot and I need to be able to format the toString so that it displays the cost with 2 decimal places. I already did some research on rounding and implemented the BigDecimal rounding method:
public static double round(double unrounded, int precision, int roundingMode) {
BigDecimal bd = new BigDecimal(unrounded);
BigDecimal rounded = bd.setScale(precision, roundingMode);
return rounded.doubleValue();
}
private double baseCost() {
double cost = (weightInOunces * costPerOunceInDollars);
cost = round(cost, 2, BigDecimal.ROUND_HALF_UP);
return cost;
}
@Override
public String toString() {
return "From: " + sender + "\n" + "To: " + recipient + "\n"
+ carrier + ": " + weightInOunces + "oz" + ", "
+ baseCost();
}
However, when it goes to print the value $11.50, it comes out at $11.5. I know how to format a decimal in a System.out.format() style, but I'm not sure how that could be applied to a toString. How could I format this so that all decimals are displayed to two values? I'm also wondering if I should even use BigDecimal, seeing as that has not been introduced in the class yet. Are there any other easy to implement rounding methods that will also format the display of the double value? Or should I just format the decimal within the toString method?
You could apply DecimalFormat
in toString
. Regarding the appropriateness of BigDecimal
, if you are dealing with money, which you are, where precision is required, use BigDecimal.
@Override
public String toString() {
DecimalFormat format = new DecimalFormat("#.00");
return "From: " + sender + ... + format.format(baseCost());
}
If you return BigDecimal
instead of double
from your round
method, the floating precision will not be lost.