0

I need to divide a with b and round that number to a n number of decimals. example : a = 2 b = 52 n = 5 , Solution = 0.03846. I can only use intigers!!

I've been working with decimalformat but I don't know how to make the format custom.

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

This only outputs #.### because of the format i need to make it #.######- n times of decimal.

TT.
  • 15,774
  • 6
  • 47
  • 88
Libraa
  • 17
  • 4

3 Answers3

0

Try:

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

}

Also, if the number of deciamls is dynamic, you can use:

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));
}
TechFree
  • 2,600
  • 1
  • 17
  • 18
0

You can use setMaximumFractionDigits(int) to set that

Example

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


Yogesh Patil
  • 908
  • 4
  • 14
-1

You can try this way:

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: Make sure to handle for negative inputs

Community
  • 1
  • 1
user404
  • 1,934
  • 1
  • 16
  • 32