-1

Let a be any floating point number:

float a = 13.1234567;

then I get a decimal places length from standard input:

import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int decLen = sc.nextInt();

How do I print 'a' with 'decLen' decimal places after the point? I need to print for

decLen = 3:

13.123

decLen = 6:

13.123456

decLen = 0:

13

Is there in the Java libaries any formatting method capable of this kind of tasks?

  • It is not a duplicate. This question deals with the scale of a primitive and the other formatting a number to a given scale. – user6629913 Feb 21 '18 at 16:03

1 Answers1

-1

A bit of a hack, but this will work:

    double[] doubles = {13.123, 13.123456, 13};
    for (int i = 0; i < doubles.length; i++) {
        BigDecimal bigDecimal = new BigDecimal(String.valueOf(doubles[i]));
        System.out.println("decLen = " + bigDecimal.stripTrailingZeros().scale());
    };

prints:

decLen = 3
decLen = 6
decLen = 0

Converting the float or double to a string will prevent rounding errors when creating the BigDecimal.

user6629913
  • 180
  • 1
  • 14