Kevin Cruijssen Kevin Cruijssen - 1 month ago 7
Java Question

Add variable amount of trailing zeros based on input integer

There are a lot of questions regarding rounding decimal to 2 decimals points after the comma, or adding leading zeros. I'm unable however, to find one which adds trailing zeros with a variable amount of zeros.

What I want to achieve:

With a positive integer n, I want to have the decimal 1/n with n amount of digits after the comma. So the first 10 would be:

1/1 = 1 -> 1.0
1/2 = 0.5 -> 0.50
1/3 = 1.333... -> 1.333
1/4 = 0.25 -> 0.2500
1/5 = 0.2 -> 0.20000
1/6 = 0.666... -> 0.666666
1/7 = 0.142... -> 0.1428571
1/8 = 0.125 -> 0.12500000
1/9 = 0.111... -> 0.111111111
1/10 = 0.1 -> 0.1000000000


Preferably I have the result as a String and use code which is as short as possible. So no for-loops, or all kind of Formatter settings. Preferably something like
String.format(..., n);
or some other short solution.

I did try
String.format("%f0", 1./n);
to see what it would output, but this only adds up until 7 digits (no idea how this is set up and if this is configurable). So for
String.format("%f0", 1./8);
the output is
0.1250000
missing the 8th zero.

Answer

Try the following:

String.format("%." + n + "f", (1.0/n));