round decimal to nearest 10th
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开发者_JS百科 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;
EDIT
Try this:
double d = 25.642;
String s = String.format("£ %.2f", Double.parseDouble(String.format("%.1f", d).replace(',', '.')));
System.out.println(s);
I know this is a stupid way, but it works.
精彩评论