I need to print floating point numbers with the following formatting requirements:
5.12345
should display only 5.1
5.0
should only 5
(without the .0
)
5.0176
should display only 5
(without the .01
)
I thought printf()
could do something like this... but now I can't seem to get it to work.
You can get kind of close to the results you want using "%g"
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("%.6g\n", 5.12345f);
printf("%.6g\n", 5.0f);
printf("%.6g\n", 5.0176f);
return 0;
}
Output:
5.12345
5
5.0176
"%g" will remove trailing zeros.
Sounds like you want to print 1 decimal place, and if that place is 0, drop it. This function should work fine:
// prints the float into dst, returns the number
// of chars in the manner of snprintf. A truncated
// output due to size limit is not altered.
// A \0 is always appended.
int printit(float f, char *dst, int max) {
int c = snprintf(dst, max, "%.1f", f);
if(c > max) {
return c;
}
// position prior to '\0'
c--;
while(dst[c] == '0') {
c--;
if(dst[c] == '.') {
c--;
break;
}
}
dst[c + 1] = '\0';
return c + 1;
}
int main(void) {
char num1[10], num2[10], num3[10];
printit(5.12345f, num1, 10);
printit(5.0f, num2, 10);
printit(5.0176f, num3, 10);
printf("%s\n%s\n%s\n", num1, num2, num3);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With