.
char *s1="100";
char *s2="09";
float f1 = strtof(s1, (void*) NULL);
unsigned n = strlen(s2);
float f2 = strtof(s2, (void*) NULL)/powf(10, n);
return f1 + f2;
, .
strtof(s2, (void*) NULL)/powf(10, n);
, , binary32. f1 + f2
. float
- .
, , double
.
float f1 = strtof(s1, (void*) NULL);
unsigned n = strlen(s2);
double f2 = strtod(s2, (void*) NULL)/pow(10, n);
return f1 + f2;
FP , , , 1 . .
long l1 = strtol(s1, (void*) NULL, 10);
long l2 = strtol(s2, (void*) NULL, 10);
unsigned n = strlen(s2);
long p10 = pow10(n);
long sum = l1*p10 + l2;
return 1.0f*sum/p10;
This works well if s1
negative. Also OK with s2
as negative, except for the extra code needed to extract the width of the digit than strlen(s2)
.
Otherwise, it is difficult to concatenate strings and convert. I recommend float strof()
over double atof()
as 1) atof()
does not have a specific behavior on overflow, 2) atof()
uses double
math, which can be slower.
size_t l1 = strlen(s1);
size_t l2 = strlen(s1);
char buffer[l1 + 1 + l2 + 1];
strcpy(buffer, s1);
buffer[l1] = '.';
strcpy(buffer + l1 + 1, s1);
return strtof(buffer, (void *) NULL);
source
share