tags:

views:

202

answers:

5

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

A: 

No, the above code doesn't round a whole number to the nearest 10th. It's just that there are no smaller fractions involved. Try this

double finalPriceRounded = Math.round(10 * finalPrice) / 10;
David M
how could Math.Round starts with an uppercase char? `Math.round`?
Martijn Courteaux
thanks for the reply. thats rounding to the nearest whole number e.g when i put in 3.2 the answer show be £5.40 approx, your code gives me £5.00 approx, my code gives me £5.4399999999 approx
Tuffy G
+6  A: 

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...

Jon Skeet
+2  A: 

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.

Jerome
MAGICAL.lolworked. so by says '0' it means physically stick 0 as the final number no matter what?
Tuffy G
yes, it does mean that.
Jerome
sweet, thanks for your help. i posted the same thing in a different forum, after 4 hours they sarcastically reffered me to google.(which i tried before)you guys where super fast lol
Tuffy G
A: 

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.

Martijn Courteaux
sorry, that didn't work
Tuffy G
+4  A: 

This outputs 2.40

BigDecimal bd = new BigDecimal(2.44);
System.out.println(bd.setScale(1,RoundingMode.HALF_UP).setScale(2));
Peter Lindqvist