我需要将数字的小数位四舍五入为n个数字

时间:2019-06-13 06:39:35

标签: java

我需要将a与b相除并将该数字四舍五入为n个小数。 例如:a = 2 b = 52 n = 5,溶液= 0.03846。 我只能使用Intigers!

我一直在使用十进制格式,但是我不知道如何自定义格式。

DecimalFormat nstevilo = new DecimalFormat("#.###");//I need to change ### to a n-number.
    if(x<y) {
    double a = x/y;
    System.out.print(nstevilo.format(a));
    }

由于我需要将其格式设置为#。######-n次小数,因此仅输出#。###。

3 个答案:

答案 0 :(得分:0)

尝试:

private static DecimalFormat df = new DecimalFormat("0.00000");

public static void main(String[] args)
{
        double d = 2 / (double) 52;
        System.out.println(df.format(d));

}

此外,如果deciaml的数量是动态的,则可以使用:

private static DecimalFormat df = new DecimalFormat();

public static void main(String[] args)
{
            df.setMaximumFractionDigits(5);
            double d = 2 / (double) 52;
            System.out.println(df.format(d));
}

答案 1 :(得分:0)

您可以使用setMaximumFractionDigits(int)进行设置

示例

DecimalFormat df = new DecimalFormat();
double d = 13/7.0;
System.out.println(d); // 1.8571428571428572
System.out.println(df.format(d)); //1.857
df.setMaximunFractionDigits(4);
System.out.println(df.format(d)); //1.8571


答案 2 :(得分:-1)

您可以尝试这种方式:

int d = x / y; 
for (int i = 0; i <= n; i++) { 
            System.out.print(d); 
            x = x - (y * d); 
            if (x == 0) 
                break; 
            x = x * 10; 
            d = x / y; 
            if (i == 0) 
                System.out.print("."); 
        } 

Details here

P.S:请确保处理负输入