Skip to content

Commit

Permalink
karm-io: Better handling of negatives for floats in general.
Browse files Browse the repository at this point in the history
  • Loading branch information
sleepy-monax committed Dec 18, 2024
1 parent 4202ec6 commit 4b16492
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
19 changes: 8 additions & 11 deletions src/libs/karm-io/aton.h
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,13 @@ static inline Opt<f64> atof(_SScan<E> &s, AtoxOptions const &options = {}) {
f64 fpart = 0.0;
i64 exp = 0;

bool negDot = s.skip("-.");
bool neg = s.skip('-');

if (not negDot) {
if (s.peek(0) != '.' or not _parseDigit(s.peek(1), options)) {
ipart = try$(atoi(s, options));
}
if (s.peek(0) != '.' or not _parseDigit(s.peek(1), options)) {
ipart = try$(atoi(s, options));
}

if (negDot or s.skip('.')) {
if (s.skip('.')) {
f64 multiplier = (1.0 / options.base);
while (not s.ended()) {
auto maybeDigit = _nextDigit(s, options);
Expand All @@ -119,11 +117,10 @@ static inline Opt<f64> atof(_SScan<E> &s, AtoxOptions const &options = {}) {
exp = maybeExp.unwrap();
}

if (negDot)
return -fpart * pow(options.base, exp);
if (ipart < 0)
return ipart - fpart * pow(options.base, exp);
return ipart + fpart * pow(options.base, exp);
auto result = ipart + fpart * pow(options.base, exp);
if (neg)
return -result;
return result;
}

#endif
Expand Down
4 changes: 4 additions & 0 deletions src/libs/karm-io/tests/test-aton.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ test$("atof") {
expect$(Math::epsilonEq(try$(Io::atof("-.1"s)), -.1));
expect$(Math::epsilonEq(try$(Io::atof("-.5"s)), -.5));

expect$(Math::epsilonEq(try$(Io::atof("-0.0"s)), -0.0));
expect$(Math::epsilonEq(try$(Io::atof("-0.1"s)), -0.1));
expect$(Math::epsilonEq(try$(Io::atof("-0.5"s)), -0.5));

return Ok();
}

Expand Down

0 comments on commit 4b16492

Please sign in to comment.