Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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);
like image 325
Swanand Avatar asked Apr 12 '20 07:04

Swanand


1 Answers

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
like image 115
backdoor Avatar answered Sep 20 '22 16:09

backdoor