i.e. can printf
be told to ignore zero when it precedes the decimal point?
views:
266answers:
7See the printf spec, and the precision section. You can do printf("%+0.4f", -0.5);
Sure it can, but I'm afraid you won't be too happy with my answer:
printf("-.5", -0.5);
I would try something like:
char *_rm0_(double d, char *_buff){
sprintf(_buff, "%f", d);
if( (int)d==0 ){
_buff++;
if(d<0) _buff[0]='-';
}
return _buff;
}
int main() {
double my_double1=0.5, my_double2=-0.5;
char _buff[10][10];
printf(" value: %s 2nd val: %s\n", _rm0_(my_double1, _buff[0]), _rm0_(my_double2, _buff[1]) );
return 0;
}
Convert your double or float to a char then:
while (*yourChar != '\0') {
if (yourDoubleBeforeConversion > 1.0 && yourDoubleBeforeConversion < -1.0) {
continue;
}
if(*yourChar == '.') {
yourChar--;
*yourChar = '';
}
else {
}
}
Explination:
- while loop determines when the char ends.
- If the double you had is greater than 1 then there is no point in trimming.
- If it isn't keep checking for a ".".
- When one is found go before and delete the zero.
With all the things that are specified in ISO C99, this is not possible. The documentation for the conversion specifiers says:
f,F: [...] If a decimal-point character appears, at least one digit appears before it. [...]
e,E: [...] there is one digit (which is nonzero if the argument is nonzero) before the decimal-point character [...]
g,G: [...] is converted to style
f
ore
[...]
Since the other conversion specifiers would not print a decimal floating-point number, this is impossible at all. Unless you find a vendor extension that introduces another conversion specifier. But then your program would not be strictly valid C anymore.
The best workaround that comes to my mind is:
double number = 0.5;
char buf[80];
char *number = buf;
if (snprintf(buf, sizeof buf, "%f", number) <= 0)
goto cannot_happen;
while (*number == '0')
number++;
printf("%s\n", number);