Round decimal to the nearest 10th

I need to round my answer to the nearest tenth.

    double finalPrice = everyMile + 2.8;
    DecimalFormat fmt = new DecimalFormat("0.00");
    this.answerField.setText("£" + fmt.format(finalPrice) + " Approx");

the code above rounds the integer to the nearest 10th, however it rounds the decimal. e.g. 2.44 should be rounded to 2.40

+5
source share
5 answers

Change the pattern bit to a hard code of finite zero:

double finalPrice = 2.46;
DecimalFormat fmt = new DecimalFormat("0.0'0'");
System.out.println("£" + fmt.format(finalPrice) + " Approx");

Now, if you are manipulating real money, you better not use double, but int or BigInteger.

+9
source

Use BigDecimalinstead.

In fact, you really don't want to use binary floating point for monetary values.

EDIT: round() , . , ( , , ):

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);
    }
}

, ...

+10

Output 2.40

BigDecimal bd = new BigDecimal(2.44);
System.out.println(bd.setScale(1,RoundingMode.HALF_UP).setScale(2));
+6
source

Try the following:

double finalPriceRoundedToNearestTenth = Math.round(10.0 * finalPrice) / 10.0;
+1
source

EDIT

Try the following:

double d = 25.642;
String s = String.format("£ %.2f", Double.parseDouble(String.format("%.1f", d).replace(',', '.')));
System.out.println(s);

I know this is stupid, but it works.

0
source

All Articles