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?
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?
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
Print the result of String.format(String, Object...)
(which is the same as printf
with an extra step), or use a BigDecimal
(if you want a type with arbitrary precision).
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));