Swanand
Swanand

Reputation: 117

Java - How to use a variable(non hardcoded) value in printf statement after decimal point?

I want to use a non hard coded value after decimal point in printf statement . Below is my code . Instead of 4 I want to set to x.

int x = sc.nextInt();
double d=103993d/33102d;
System.out.printf("%.4f", d);

Upvotes: 5

Views: 150

Answers (2)

Ranjeet
Ranjeet

Reputation: 21

Use String in printf.

    int x = sc.nextInt();
    double d=103993d/33102d;
    String s1 = Integer.toString(x);
    String s="%."+s1+"f";
    System.out.printf(s,d);

Upvotes: 0

backdoor
backdoor

Reputation: 901

Declare a variable and concatenate with the formatting string as below

double d=103993d/33102d;
int x=9;
System.out.printf("%."+x+"f", d);

OUTPUT:-

3.141592653

Upvotes: 6

Related Questions