0

I have two double number a and b

double a = 1.01, b = 1.2345678

then printf("%.4f %.4f", a, b) will output

1.0100  1.2345

but I want to output

1.01 1.2345

that is, remove the useless 0s.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user2848932
  • 776
  • 1
  • 14
  • 28
  • 4
    they are not useless, `1.01` is a number between `1.005` and `1.0149999999...`, but `1.0100` is a number between `1.00995` and `1.010049999999...`. – mch Oct 29 '15 at 07:38
  • 1
    Unrelated to programming: in general science, it is considered proper style to keep the number of digits consistent throughout your calculations. So the first form would be the most correct in most cases. – Lundin Oct 29 '15 at 07:47

3 Answers3

2

%.4f will always prints up to 4 decimal by padding zeros. You can remove %.4f and use %g for printing exact value with out padding zeros

g,G The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.

Dilip Kumar
  • 1,736
  • 11
  • 22
2

Not excactly what you want but you could use %g instead of %f like below:

  double a = 1.01, b = 1.2345678;
  printf("%.4g %.4g\n", a, b);

The precision value is interpreted differently in "g" format than in "f" format. The precision for "f" specifies the number of digits after the decimal point. The precision for "g" specifies the maximum number of significant digits printed.

101010
  • 41,839
  • 11
  • 94
  • 168
2

If you specify a width ... then you're going to get that width.

Simply use "%g" or "%f" instead.

From the "man" page:

http://linux.die.net/man/3/printf

g, G

The double argument is converted in style f or e (or F or E for G conversions). The precision specifies the number of significant digits. If the precision is missing, 6 digits are given; if the precision is zero, it is treated as 1. Style e is used if the exponent from its conversion is less than -4 or greater than or equal to the precision. Trailing zeros are removed from the fractional part of the result; a decimal point appears only if it is followed by at least one digit.

Itay Sela
  • 942
  • 9
  • 26
paulsm4
  • 114,292
  • 17
  • 138
  • 190