Reputation: 11012
Having char double[] = "1.2345678";
, I have to trim all digits in 4nd place and above after the .
in this char *
i.e make it to "1.234"
.
Upvotes: 1
Views: 275
Reputation: 5917
One obvious solution is to replace a character by NUL
, like so:
char *foo = strdup("1.2345678"); // FIXME: check return value
foo[5] = '\0';
Note that the exact position might differ, depening on how many digits appear before the '.' character.
Iterate over the string foo
, change the state in passed_dot
if you come across '.', and insert a NUL
after 4 more characters:
char *p = foo;
int i = 0;
int passed_dot = 0;
while (p && *p) {
if (*p == '.') passed_dot = 1;
if (passed_dot) i++;
if (i == 4) {
*p = '\0';
break;
}
p++;
}
If you can't afford to buy more RAM, you may strdup()
the resulting string and free()
the old one in order to save memory:
new_str = strdup(foo); // and don't forget to check for NULL
free(foo);
Upvotes: 2
Reputation: 42175
Note that
char * double= "1.2345678";
declares a string literal. This is const so can't be directly modified. To get a modifiable string, you could declare it as
char double[] = "1.2345678";
or
char* double = strdup("1.2345678");
then insert a nul character as suggested in other answers.
Upvotes: 2
Reputation: 409176
Find the '.'
, advance four steps, and put the string terminator there.
Watch out so you don't pass the string terminator yourself, if the number contains less than three digits after the dot.
To help you find the dot, look up the strchr
function.
Upvotes: 3