-1

I declare a variable double MyDouble;.

If I then set MyDouble = 1000.0 / 3.0; and then printf("%g", MyDouble); gives 333.333 so it's lost some precision.

If I use printf("%lf", MyDouble); I get the precision.

The down side is if I now set MyDouble = 5.0 / 2.0; and use printf("%lf", MyDouble); I get 2.500000, so trailing zeroes.

As a general case, how can I have the precision without the trailing zeroes. I could write the double to a string using snprintf and the %lf format and then write a subroutine to strip trailing zeroes, but there must be an easier way.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
user1228123
  • 424
  • 4
  • 15
  • 1
    Link to std::printf documentation including format specifiers: http://en.cppreference.com/w/cpp/io/c/fprintf – Richard Critten Jun 21 '16 at 09:51
  • 4
    You either want that much precision or you don't. – Lightness Races in Orbit Jun 21 '16 at 09:52
  • 1
    `l` length modifier has no effect on `f` specifier. – jxh Jun 21 '16 at 09:54
  • The documentation says the l length modifier has no effect but if I leave it off I get 333.333 so it is having an effect on my compiler. – user1228123 Jun 21 '16 at 09:58
  • 1
    This is not even a programming problem. When doing any form of scientific work, it is custom to specify the number of decimals used by all your calculations and then stick to that consistently. For example if you are writing a scientific report about two values, 123.45 and 123, you would write `123.45` and `123.00` respectively. They teach this in any beginner-level science class. – Lundin Jun 21 '16 at 10:53
  • This is not related to C++, but the C standard library `printf` family. – too honest for this site Jun 21 '16 at 11:58

2 Answers2

1

The precision of the g conversion specifier controls the maximum number of significant digits (see C.2011§7.21.6.1¶4). Precision is specified by a number following a decimal point. It seems you want 9 significant digits. So, try:

printf("%.9g", MyDouble);
jxh
  • 69,070
  • 8
  • 110
  • 193
  • [Demo on Ideone.](http://ideone.com/X09o3i) – jxh Jun 21 '16 at 10:06
  • Thank you jxh. That would give precison to the %f specifier but not remove trailing zeroes. "%.17g" does what I need as it formats the number to up to the full 17 characters (inc the decimal point and then strips unnecessary zeroes. – user1228123 Jun 21 '16 at 10:11
  • The answer was meant to have `g`, as stated in my first sentence. The code with `f` was a typo. – jxh Jun 21 '16 at 10:19
0

You can try like this to avoid trailing zero.

double a= 5.0;
double b = 2.0;
printf("%.2lf\n", a/b);
Mr. Perfectionist
  • 2,605
  • 2
  • 24
  • 35