Skip to content

Instantly share code, notes, and snippets.

@lukem512
Last active January 16, 2022 17:10
Show Gist options
  • Save lukem512/7f46928ae9a3934a4b416655f36fea3b to your computer and use it in GitHub Desktop.
Save lukem512/7f46928ae9a3934a4b416655f36fea3b to your computer and use it in GitHub Desktop.
ASCII to Float in C
/* Onlu needed for printf() */
#include <stdio.h>
/* Boolean types - comment if not needed */
typedef int bool;
#define true 1
#define false 0
/* !Boolean types */
/* There are also built-in functions for these */
bool isdigit(char c) {
return c >= '0' && c <= '9';
}
bool isspace(char c) {
return c == ' ';
}
/* Definition of atof */
double atof(char s[]) {
double val, power;
int i, sign;
// Skip initial whitespace
for (i = 0; isspace(s[i]); i++);
// Look for sign prefix
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-') ++i;
// Compute the value for all digits before the point
for (val = 0.0; isdigit(s[i]); ++i) {
val = 10.0 * val + (s[i] - '0');
}
// Compute the fractional power for all digits after the point
if (s[i] == '.') {
++i;
}
for (power = 1.0; isdigit(s[i]); ++i) {
val = 10.0 * val + (s[i] - '0');
power *= 10.0;
}
return (sign * val / (power));
}
int main(int argc, char** argv) {
double res;
res = atof("0.123456");
printf("0.123456 is now %f\n", res);
res = atof("-123.234534");
printf("-123.234534 is now %f\n", res);
res = atof("19293949");
printf("19293949 is now %f\n", res);
res = atof("1233333333.1");
printf("1233333333.1 is now %f\n", res);
// Rounding error!
res = atof("-0.12399999");
printf("-0.12399999 is now %f\n", res);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment