1

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.

Kevin Cruijssen
  • 8,426
  • 8
  • 49
  • 114

3 Answers3

2

Try the following:

String.format("%." + n + "f", (1.0/n));
Robert Kock
  • 5,572
  • 1
  • 10
  • 19
  • Hmm.. for `n = 18` it results in `0.0555555555555555500` instead of `0.055555555555555555` :S – Kevin Cruijssen Oct 12 '16 at 09:57
  • This is due to the fact a double has only 17 significant digits. – Robert Kock Oct 12 '16 at 10:33
  • Yeah, came to the same conclusion closely after making the comment. I guess I should go look into `BigDecimals` and a similar format based on the one you've provided. – Kevin Cruijssen Oct 12 '16 at 11:04
  • Ok, guess I'll have to use `BigDecimal.ONE.divide(new BigDecimal(n), n, RoundingMode.CEILING).toString()` instead. Will keep your answer as accepted though, since it works as a charm up until 17 and is using a short `String.format` as I preferred for this. Thanks again. – Kevin Cruijssen Oct 12 '16 at 11:19
0

In case you dont get the "single" format to work, there is an easy workaround: create the desired output in two steps.

Example for your 1/8 case:

  1. value = "0.125";
  2. you want a total length of 10 ( 0 . and 8 digits!), so simply create a another string padding = "00000";

And return value + padding

The padding can be done easily using String.format(), too; see here for various examples.

Community
  • 1
  • 1
GhostCat
  • 127,190
  • 21
  • 146
  • 218
0

Use the NumberFormat class and set setMaximumFractionDigits and setMinimumFractionDigits

Example

private static void resolveDecimalPlaces(int i) {
    final NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(i);
    nf.setMinimumFractionDigits(i);
    nf.setRoundingMode(RoundingMode.HALF_UP);

    System.out.println(nf.format(1.0 / i));
}
Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 43,054
  • 16
  • 58
  • 83