You could make your job easier with %.0f:
Code:
double get_first_digit(double number) {
char buffer[BUFSIZ];
sprintf(buffer, "%.0f", number);
if(*buffer) {
return buffer[strlen(buffer) - 1] - '0';
}
return 0;
}
But anyway, using a string is a bad idea in my opinion. You use lots of extra memory, and sprintf()'s probably pretty slow too. The mathematical way isn't much harder, if any.
I think you're right, but for whatever reason I was under the impression the floor() was needed. I don't remember what prompted me to think that.
Casting a floating point number to an int would indeed have the same effect as flooring it. But using floor() and modf() instead of a cast to an integral type is a much better idea, because a floating point number can easily store values that cannot be represented in any integral type. If you casted one of those values to (int), you'd get an integer overflow.
So floor() exists so that you can round a number without risk of overflow.
Anyway, you could also use something like this:
Code:
double get_first_digit(double number) {
return floor(floor(number/10)*10 - number);
}
That's probably a bad way to do it . . . perhaps something like this, then.
Code:
double get_first_digit(double number) {
return floor(fmod(number, 10));
}
To get the first decimal digit, of course.