Skip to content

Commit

Permalink
flisp: use jl_strtof_c to convert strings to float
Browse files Browse the repository at this point in the history
indirect conversion (string->double->float) will lose precision
  • Loading branch information
inkydragon committed Sep 14, 2024
1 parent 346f38b commit 9df7b0e
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/flisp/read.c
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ int isnumtok_base(fl_context_t *fl_ctx, char *tok, value_t *pval, int base)
int64_t i64;
uint64_t ui64;
double d;
float f;

if (*tok == '\0')
return 0;
if (!((tok[0]=='0' && tok[1]=='x') || (base >= 15)) &&
Expand All @@ -44,11 +46,15 @@ int isnumtok_base(fl_context_t *fl_ctx, char *tok, value_t *pval, int base)
if (pval) *pval = mk_double(fl_ctx, d);
return 1;
}

// NOTE(#49689): DO NOT convert double to float directly,
// indirect conversion (string->double->float) will lose precision.
f = jl_strtof_c(tok, &end);
// floats can end in f or f0
if (end > tok && end[0] == 'f' &&
(end[1] == '\0' ||
(end[1] == '0' && end[2] == '\0'))) {
if (pval) *pval = mk_float(fl_ctx, (float)d);
if (pval) *pval = mk_float(fl_ctx, f);
return 1;
}
}
Expand All @@ -60,11 +66,15 @@ int isnumtok_base(fl_context_t *fl_ctx, char *tok, value_t *pval, int base)
if (pval) *pval = mk_double(fl_ctx, d);
return 1;
}

// NOTE(#49689): DO NOT convert double to float directly,
// indirect conversion (string->double->float) will lose precision.
f = jl_strtof_c(tok, &end);
// floats can end in f or f0
if (end > tok && end[0] == 'f' &&
(end[1] == '\0' ||
(end[1] == '0' && end[2] == '\0'))) {
if (pval) *pval = mk_float(fl_ctx, (float)d);
if (pval) *pval = mk_float(fl_ctx, f);
return 1;
}
}
Expand Down

0 comments on commit 9df7b0e

Please sign in to comment.