What is the formatter to make sure that + or - signs are always shown in front of the float value in printf() in C?
I haven't done C in a while, so where can I find a good reference on the web, any suggestions are appreciated
views:
49answers:
2
+2
A:
Put a +
sign after the %
but before the field width, precision specifier, or the f
. For example: "%+10.2f" for a ten character wide field with two digits after the decimal.
From printf(3) http://linux.die.net/man/3/printf:
+
A sign (+ or -) should always be placed before a number produced by a signed conversion. By default a sign is used only for negative numbers. A + overrides a space if both are used.
idealmachine
2010-10-16 20:40:23
+1: but maybe add an example for clarity, e.g. `printf("x = %+g\n", x);` ?
Paul R
2010-10-16 20:42:34
+1
A:
"%+f" is what you're looking for (though note that when you print it, you'll actually be printing a double, not a float -- a float is implicitly promoted to double when passed to a function that doesn't have a prototype or for a variadic argument).
Jerry Coffin
2010-10-16 20:42:50