Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round decimal to nearest 10th

Tags:

java

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

like image 978
Tuffy G Avatar asked Dec 11 '09 12:12

Tuffy G


4 Answers

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

like image 75
Jon Skeet Avatar answered Nov 11 '22 18:11

Jon Skeet


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.

like image 41
Jerome Avatar answered Nov 11 '22 17:11

Jerome


This outputs 2.40

BigDecimal bd = new BigDecimal(2.44);
System.out.println(bd.setScale(1,RoundingMode.HALF_UP).setScale(2));
like image 40
Peter Lindqvist Avatar answered Nov 11 '22 17:11

Peter Lindqvist


Try the following:

double finalPriceRoundedToNearestTenth = Math.round(10.0 * finalPrice) / 10.0;
like image 29
Erik B Avatar answered Nov 11 '22 18:11

Erik B