Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string format with %g in C

How do I create a string so that it formats floating point numbers to have no trailing decimal point or digits when it is an integer, but to NOT switch to scientific notation for larger numbers?

When I do:

float myFloat= 15.6f;
float myInt = 5.0f;
float myLarge = 7000000.0f;
sprintf(out, "my float is %g", myFloat);
sprintf(out, "my int is %g", myInt);
sprintf(out, "my large is %g", myLarge);

I get something like:

my float is 15.6
my int is 5
my large is 7e+07f

I want all a single format string that will give 15.6, 5, and 700000.

Edited cause comments don't do formatting:

that's what I thought. but a wrapper is pretty inconvenient though as the format strings are embedded in longer format strings:

sprintf(buf, "%d %g", myInt, myFloat);

how do you wrap that?

sprintf(buf, "%d %g", myInt, Wrapper(myFloat));??

what should Wrapper return? Or worse:

sprintf(buf, "%d %s", myInt, Wrapper(myFloat));?? 
like image 603
sean riley Avatar asked May 06 '09 00:05

sean riley


People also ask

What does the %g operator format?

Each format sequence is matched with an element of the tuple, in order. The following example uses "%d" to format an integer, "%g" to format a floating-point number (don't ask why), and "%s" to format a string: >>> 'In %d years I have spotted %g %s.

What is %p format string?

%p expects the argument to be of type (void *) and prints out the address. Whereas %x converts an unsigned int to unsigned hexadecimal and prints out the result.

What does %s mean in Sprintf?

The simplest format specification contains only the percent sign and a type character (for example, %s). The percent sign: If a percent sign (%) is followed by a character that has no meaning as a format field, the character is simply copied to the buffer.


2 Answers

I don't think you can get this with %g, as %g gives you the shorter of %e or %f.

So, I don't think there's a single printf argument that satisfies you. For 15.6, you could use %2.1f; for 7000000, you could use %7.0f.

Your best bet is probably to write a wrapper function that would look at the size of your value and apply the correct printf argument.

like image 31
joce Avatar answered Sep 28 '22 07:09

joce


You can format with "%.*f", which allows you to pass the precision as a separate parameter to e.g. sprintf. I've used this in the past when I wanted to display 0, 1, 2, or maybe 3 digits nicely without extra trailing 0's. Write a little helper function which takes the double/float and returns an integer precision (by multiplying by 1000 and then doing modulo 10, 100, 1000). Then call sprintf with "%.*f", call the helper function, and pass the float.

like image 82
Mike Kale Avatar answered Sep 28 '22 06:09

Mike Kale