Commit db80a9a2 authored by h2so5's avatar h2so5

fix mrb_flo_to_str() exponent problem

parent 41a77111
...@@ -130,9 +130,9 @@ mrb_flo_to_str(mrb_state *mrb, mrb_value flo, int max_digit) ...@@ -130,9 +130,9 @@ mrb_flo_to_str(mrb_state *mrb, mrb_value flo, int max_digit)
} }
else { else {
int digit; int digit;
int m; int m = 0;
int exp; int exp;
int e = 0; mrb_bool e = FALSE;
char s[48]; char s[48];
char *c = &s[0]; char *c = &s[0];
...@@ -141,39 +141,41 @@ mrb_flo_to_str(mrb_state *mrb, mrb_value flo, int max_digit) ...@@ -141,39 +141,41 @@ mrb_flo_to_str(mrb_state *mrb, mrb_value flo, int max_digit)
*(c++) = '-'; *(c++) = '-';
} }
exp = (int)log10(n); exp = (n > 1) ? floor(log10(n)) : -ceil(-log10(n));
if ((exp < 0 ? -exp : exp) > max_digit) { if ((exp < 0 ? -exp : exp) >= max_digit) {
/* exponent representation */ /* exponent representation */
e = 1; e = TRUE;
m = exp; n = n / pow(10.0, exp);
if (m < 0) {
m -= 1;
}
n = n / pow(10.0, m);
m = 0;
} }
else { else {
/* un-exponent (normal) representation */ /* un-exponent (normal) representation */
if (exp > 0) {
m = exp; m = exp;
if (m < 0) {
m = 0;
} }
} }
/* puts digits */ /* puts digits */
while (max_digit >= 0) { while (max_digit >= 0) {
mrb_float weight = pow(10.0, m); mrb_float weight = pow(10.0, m);
digit = (int)floor(n / weight + FLT_EPSILON); mrb_float fdigit = n / weight;
if (m < -1 && fdigit < FLT_EPSILON) {
if (e || exp > 0 || m <= -abs(exp)) {
break;
}
}
digit = (int)floor(fdigit + FLT_EPSILON);
if (m == 0 && digit > 9) {
n /= 10.0;
exp++;
continue;
}
*(c++) = '0' + digit; *(c++) = '0' + digit;
n -= (digit * weight); n -= (digit * weight);
max_digit--; max_digit--;
if (m-- == 0) { if (m-- == 0) {
*(c++) = '.'; *(c++) = '.';
} }
else if (m < -1 && n < FLT_EPSILON) {
break;
}
} }
if (e) { if (e) {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment