I have this policy to never use floating point if I can... Here's why... A simple approach to this "conversion" would be:
Code:
#define _GNU_SOURCE
#include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h> // for basename().
#include <ctype.h>
#include <errno.h>
int main(int argc, char **argv)
{
char *err;
double t; /* double have 53 bits precision.
Maximum value (with cents): +/-90071992547409.91 */
int64_t i;
int f;
if ( ! *++argv )
{
fprintf( stderr, "Usage: %s \"<value>\"\n", basename( *(argv - 1) ) );
return EXIT_FAILURE;
}
/* Example of conversion, testing for errors */
errno = 0;
t = strtod(*argv, &err);
if ( ( *err && !isdigit(*err) ) || errno == ERANGE )
{
fputs( "ERROR: Cannot convert.\n", stderr );
return EXIT_FAILURE;
}
i = t; // holds the integer part
f = ( t - i ) * 100; // holds the fractional part (cents).
printf( "%" PRIi64 ".%d\n", i, f );
return EXIT_SUCCESS;
}
If you run the program, as below:
Code:
$ ./test 3.14
3.14
$ ./test.9.44
9.44
$ ./test 9.ab
ERROR: Cannot convert.
But if you do:
Why? 0.3 isn't exact in binary floating point!