Pregunta

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?

¿Fue útil?

Solución

How about the 'obvious'.....

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

Otros consejos

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));
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top