ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
I get a result like 4.300000. Is there any way to automatically realise that it should be 4.3, and print that? Hopefully quite a fast way. I know that it can be done with many sprintfs, and looking through the strings and working out where the zero's start, and then using those strings instead, but I was hoping there would be an easier way.
That appears to round it to 1 decimal place, so 4 is printed as 4.0, and 4.32 is printed as 4.3 - I need a way which will automatically cut off any excess 0's, so 4 would be 4, 4.3 would be 4.3 and 4.32 would be 4.32. Thank you.
4 works, but 4.302 doesn't. DJGPP might not have snprintf() because it should be in the standard C library. You can just use sprintf() since %f won't show over 100 characters anyway.
One last try here:
char *round(double num)
static char buf;
sprintf(buf, "%f", num);
// Get to the end of the string
for(i = 0;buf[i];i++); // Whole loop
// Work back until the first non-zero character
for(i--;buf[i] == '0';i--); // Whole loop
if(buf[i] == '.')
buf[i+1] = '\0';
It's because round() is using a static buffer. The problem could be fixed with dynamic memory allocation, but the calling function would have to remember to free the memory. As it is now you just have to seperate calls to round() into different statements.