1
class Test
{
    public static void main(String[] args)
    {
        double arr[] = {1.2, 1.23, 1.234, 1.2345};
        System.out.printf("%f %f %f %f", arr[0], arr[1], arr[2], arr[3]);
    }
}

For example if I don't know how many numbers there are after dot (.) and I want to print them all in printf() without zeros (1.200000) ( likewise in println() ). If so, how?

Denys_newbie
  • 1,140
  • 5
  • 15
  • Do you mean that if `arr` were `{ 1.2, 1.20, 1.200, 1.2000 }`, you'd want the output to be `1.2 1.20 1.200 1.2000` as well? – Sweeper Jun 09 '20 at 10:34
  • no I mean if have an array of double/float values and If want to output it using printf() but without subsequent zeros (1.200000) and without rounding off number (1.2345 prints as 1.23) and if I don't know how many digits after dot (.) – Denys_newbie Jun 09 '20 at 10:38
  • 1
    When you see `1.2` in your code, that value isn't actually 1.2. It's something very close to it, because 1.2 can't be accurately expressed in binary. So if you _really_ don't want any rounding, you wouldn't get 1.2. You would need to specify a "_maximum_ number fractional digits" that you need. – Sweeper Jun 09 '20 at 10:45

2 Answers2

1

you can use paramaters, eg: %1.2f, but this round the number. I'm not sure is that what you want.

    float f = 1.225f;
    System.out.printf("%f \t %1.2f \t %1.4f", f,f,f);

you can you BigDecimal is better solution, but problem with zeros on the end.

    float f = 1.225f;
    BigDecimal number1 = new BigDecimal(f);
    BigDecimal number2 = new BigDecimal(f).setScale(2, RoundingMode.HALF_DOWN);
    BigDecimal number3 = new BigDecimal(f).setScale(4, RoundingMode.HALF_DOWN);
    System.out.println(number1+"\n"+number2+"\n"+number3);

but if you put in BigDecimal number as string, will be printed with precission of this string:

    BigDecimal bd1 = new BigDecimal("1.123");
    BigDecimal bd2 = new BigDecimal("1.123000");
    System.out.println(bd1+"\n"+bd2);

so you can use this trick to your case:

    float f = 1.225000f;
    BigDecimal snumber1 = new BigDecimal(f+"");
    System.out.println(snumber1);
Victor1125
  • 642
  • 5
  • 16
1

Use %s as the formatter:

System.out.printf("%s", 1.2); // output: 1.2

%s converts the number to a string with the usual toString method, which includes only as many digits as necessary to tell a number apart from its neighbors.

Joni
  • 108,737
  • 14
  • 143
  • 193