how am I supposed to find the number of digits of decimal numbers in c? ex. find how many digits are in 123.4567?!
CodePudding user response:
how am I supposed to find the number of digits of decimal numbers in c? ex. find how many digits are in 123.4567?
Start by converting it to a string.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char input[] = "123.456";
int i, d = 0, count = 0, len = strlen(input);
for (i = 0; i < len; i ) {
if (input[i] == '.') {
if ( d == 1) {
printf("int count %d\n", count);
if (i == 0) {
break;
}
continue;
}
// 2 or more decimal points.
break;
}
if (isdigit(input[i])) {
count ;
continue;
}
// Found a non-digit non-decimal point.
if (i == 0) {
printf("int count %d\n", count);
}
break;
}
printf("all count %d\n", count);
}
CodePudding user response:
The "number of digits" in a floating-point number is more complicated than it sounds, and is ultimately rather meaningless.
If you say
float f = 123.4567;
that number actually has 20 decimal digits. The reason is that the number 123.4567 cannot be represented exactly in binary floating point. The closest number which can be represented as a float
is 123.45670318603515625.
If you say
double d = 123.4567;
that number has 49 digits. Type double
can't represent 123.4567 either, but since it has more precision it can get closer: 123.4566999999999978854248183779418468475341796875.
If you're reading a number in from the user, and if you're reading it in as a string (not a float
or a double
), then you can count the number of digits exactly, without as many surprises. On the other hand, you then have to worry about what answer you want if the user types something like 000123.4567000
.