I am building a program that calculates the total cost of a restaurant bill. My program is rounding $18.135 down to $18.13. This is the code that I am using to round it to two decimal places:
tip = Math.round((charge * TIP_PERCENTAGE) * 100) / 100d;
All of the variables are doubles, and charge is equal to 100.75 and TIP_PERCENTAGE is equal to 0.18.
I tried a couple of things but I have not had any luck. I want the program to round $18.135 up to $18.14.
Try this
private static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(Double.toString(value));
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
...
tip =(charge * TIP_PERCENTAGE) ;
tip = round(tip,2);