3 ms·
After converting the string to float and then multiplying by 100, round to the nearest integer. Assuming that the underlying implementation of Ruby uses sscanf
by tzs 7y ago
After converting the string to float and then multiplying by 100, round to the nearest integer.
Assuming that the underlying implementation of Ruby uses sscanf for the conversion (I'm assuming Ruby is in C or C++?), that should work.
I had some concerns about this general issue, and did some brute force testing. The following program constructs strings "0.1", "0.2", ..., "0.9", "0.01", "0.02", ..., "0.99", ..., "0.99999999", uses sscanf to turn them into doubles, multiplies by the appropriate power of 10, rounds to the nearest integer, and checks if that is right.
#include <stdio.h>
#include <math.h>
int main(void)
{
int len = 1;
unsigned long div = 10;
char num[30];
while (len < 9)
{
for (unsigned long i = 1; i < div; ++i)
{
sprintf(num, "%.20lu", i);
num[19-len] = '.';
char * dp = num + 18 - len;
double d;
sscanf(dp, "%lf", &d);
unsigned long ci = round(d * div);
if (i != ci)
printf("%s, %lf, %lu\n", dp, d, ci);
}
++len;
div *= 10;
fprintf(stderr, "LEN=%d, DIV=%ld\n", len, div);
}
return 0;
}