Jura Brazdil
Jura Brazdil

Reputation: 1100

Output float with different number of decimals each time

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

Answers (2)

rolfl
rolfl

Reputation: 17707

How about the 'obvious'.....

System.out.printf("%." + n + "f", x);

Upvotes: 5

upog
upog

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

Related Questions