Is it possible to cast with precision in java without using the formatted printf?

Viewed 172

This line results in double value 3.33333333335

System.out.println("Average marks of " + name + " = " + (double)sum/3);

Is it possible to set a width of precision?

3 Answers

You can use DecimalFormat or BigDecimal as follows:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        int sum = 10;
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        System.out.println(Double.valueOf(decimalFormat.format((double) sum / 3)));

        // Another way
        System.out.println(new BigDecimal(String.valueOf((double) sum / 3)).setScale(2, RoundingMode.HALF_UP));

        // The better way using BigDecimal - thanks to @Andreas
        System.out.println(BigDecimal.valueOf(sum).divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP));
    }
}

Output:

3.33
3.33
3.33

One solution is to write function:

static double roundWithTwoDigits(double x) {
    return (double) Math.round(x * 100) / 100;
}

Now you can use it:

System.out.println("Average marks of " + name + " = " + roundWithTwoDigits((double) sum / 7));
Related