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

有些话、适合烂在心里 提交于 2020-06-13 01:53:07

问题


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?


回答1:


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



回答2:


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




回答3:


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


来源:https://stackoverflow.com/questions/60668820/is-it-possible-to-cast-with-precision-in-java-without-using-the-formatted-printf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!