skip to Main Content

I have different types of numbers of type float and/or double.

I want to set these numbers to a specific format of 6 digits.

Examples:

1.01234
10.1234
101.234
1012.34
10123.4
101234
1.10000
1.33000

Regardless of how a number looks, whether is has a a decimal or it doesn’t, I want it to be 6 digits.

So I have:

String s = "123.4";

I want printout to look like: 123.400

I know I can use String.format("%.3f", s) to get result of type xxx.xxx

But what if have a different number?

Check the examples below and required results:

123456 to 123456
1.2    to 1.20000
0.56   to 0.56000
0.001  to 0.00100

Note that the required result has 6 digits.

2

Answers


  1. You could use the DecimalFormat class to format your numbers, then maybe switch on the length of your number and play with the setMinimumFractionDigits, setMaximumFractionDigits, setMinimumIntegerDigits and setMaximumIntegerDigits methods to format your number with the number of leading and trailing zeros you want.

    Login or Signup to reply.
  2. You can use Math.log10(double) to discover how many digits are in the number. Create a variable format specifier using the result:

    public static String digitsDemo (double x) {
        int digits = (int) Math.log10 (x);
        String form = "%." + ( 6 - digits - 1) + "f";
        return String.format (form, x);
    }
    
    public static void testDigitsDemo () {
        double [] a = { 1.01234, 10.1234, 101.234, 1012.34, 10123.4, 101234
                      ,1.10000, 1.33000, 100.0, 1.0, 0.5, 0.25, .000000789
                      ,0.00000567, 1.0000567, 999_999, 0.000900, 1.987999999
                      };
        for (double b : a) { 
            System.out.println (digitsDemo (b));
        }
        System.out.println ();
    }
    

    Results:

      1.01234
      10.1234
      101.234
      1012.34
      10123.4
      101234
      1.10000
      1.33000
      100.000
      1.00000
      0.50000
      0.25000
      0.00000078900
      0.0000056700
      1.00006
      999999
      0.00090000
      1.98800
    

    This code has some known shortcomings:

    1. It will throw a NumberFormatException if the value is 1_000_000.0 or greater or is zero.
    2. If the number is too small, it can ignore the format and show excess digits to the right of the decimal point. This is shown in the test run results.
    3. Negative numbers have not been considered.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search