need to round my answer to nearest10th.
double finalPrice = everyMile + 2.8;
DecimalFormat fmt = new DecimalFormat("0.00");
this.answerField.setText("£" + fmt.format(finalPrice) + " Approx");
the above code rounds a whole number to the nearest 10th however it wont round a decimal. e.g 2.44 should be rounded to 2.40
Use BigDecimal
instead.
You really, really don't want to use binary floating point for monetary values.
EDIT: round()
doesn't let you specify the decimal places, only the significant figures. Here's a somewhat fiddly technique, but it works (assuming you want to truncate, basically):
import java.math.*;
public class Test
{
public static void main(String[] args)
{
BigDecimal bd = new BigDecimal("20.44");
bd = bd.movePointRight(1);
BigInteger floor = bd.toBigInteger();
bd = new BigDecimal(floor).movePointLeft(1);
System.out.println(bd);
}
}
I'd like to hope there's a simpler way of doing this...
Change a bit the pattern to hard-code the final zero:
double finalPrice = 2.46;
DecimalFormat fmt = new DecimalFormat("0.0'0'");
System.out.println("£" + fmt.format(finalPrice) + " Approx");
Now, if you're manipulating real-world money, you'd better not use double, but int or BigInteger.
This outputs 2.40
BigDecimal bd = new BigDecimal(2.44);
System.out.println(bd.setScale(1,RoundingMode.HALF_UP).setScale(2));
Try the following:
double finalPriceRoundedToNearestTenth = Math.round(10.0 * finalPrice) / 10.0;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With