Reputation: 1100
I am trying to resolve this for quite some time. What I need is a script as simple as possible that takes float 'x' and int 'n' and then outputs 'x' with 'n' number of decimals. It could be somethng like:
float x = 111.1111f;
int n = 2;
System.out.printf("%{n}f", x);
(Outputs: '111.11')
What I am mainly looking for is some kind of a formatting tool allowing you to use variables inside of string declarations. Is there a way as simple as this to make it work? If not, what is the most simple solution of my problem?
Upvotes: 0
Views: 69
Reputation: 5521
you can also use decimal formatter to achieve this
int n = 2;
float x = 111.1111f;
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(n);
System.out.println(df.format(x));
Upvotes: 2