Thread: %g doesn't print as many decimal places as %f

  1. #1
    Registered User
    Join Date
    Mar 2008

    %g doesn't print as many decimal places as %f

    Take a look at this:

    int main() {
    	double x, y;
    	x = 5;
    	y = 2.75;
    	printf("x is %f and y is %f\n", x, y);
    That will print 'x is 5.00000000 and y is 2.7500000000000' or somesuch.
    I wanted to get rid of the useless zeroes, so somebody suggested using %g instead. Problem is, that rounds to the nearest ten thousanth (four decimal places), while %f works to six (nearest millionth).

    Any ideas? If possible, I'd like to retain the functionality of %g but have six significant decimal places.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    %g only truncates closing zeroes; at least on my machine, this code
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    int main(void) {
        float b = 0.0078125f;
        printf("%f %g %6g\n", b, b, b);
        return 0;
    prints this
    0.007813 0.0078125 0.0078125
    But you should be able to specify a print format with %g just as well as with %f.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What kind of programs should I start writing?
    By Macabre in forum C++ Programming
    Replies: 23
    Last Post: 04-12-2003, 08:13 PM
  2. Getting Two Decimal Places
    By LostNotFound in forum C++ Programming
    Replies: 1
    Last Post: 03-29-2003, 07:34 PM
  3. decimal places
    By Unregistered in forum C++ Programming
    Replies: 5
    Last Post: 08-01-2002, 07:08 PM
  4. Replies: 1
    Last Post: 07-31-2002, 11:35 AM
  5. Decimal to binary conversion help needed
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 02-06-2002, 12:03 PM
Website Security Test