Skip to content

Commit

Permalink
Fix float-parsing logic
Browse files Browse the repository at this point in the history
With the float string representation fixed in Nim devel (See
nim-lang/Nim#18139), that uncovered a bug in
the logic for parsing float TOML values.

For e.g. to parse "foo = 0.123", internally, 0.1 + 0.02 + 0.003 was
done which would evaluate to 0.12300000000000001. Earlier
float stringification bug caused that value to print out as "0.123"
instead of "0.12300000000000001".

This is now fixed by using parseutils.parsefloat, which parses the
"0.123" float value as 0.123 and not 0.12300000000000001.

Fixes NimParsers#45.
  • Loading branch information
kaushalmodi committed Jun 7, 2021
1 parent 3760867 commit 3e4c2da
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/parsetoml.nim
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ import streams
import strutils
import tables
import unicode
from parseutils import parseFloat

export tables

when (NimMajor, NimMinor, NimPatch) < (1, 4, 0):
Expand Down Expand Up @@ -271,9 +273,9 @@ proc parseEncoding(state: var ParserState): TomlValueRef =
proc parseDecimalPart(state: var ParserState): float64 =
var
nextChar: char
invPowerOfTen = 10.0
firstPos = true
wasUnderscore = false
decimalPartStr = "0."

result = 0.0
while true:
Expand All @@ -293,11 +295,11 @@ proc parseDecimalPart(state: var ParserState): float64 =
raise newTomlError(state, "decimal part empty")
break

result = result + (int(nextChar) - int('0')).float / invPowerOfTen
invPowerOfTen *= 10
decimalPartStr.add(nextChar)

firstPos = false

doAssert decimalPartStr.len > 2 # decimalPartStr shouldn't still be "0." at this point
discard parseutils.parseFloat(decimalPartStr, result)

proc stringDelimiter(kind: StringType): char {.inline, noSideEffect.} =
result = (case kind
Expand Down
4 changes: 4 additions & 0 deletions tests/test1.nim
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,7 @@ file_name = "test.txt"
tomlRef.setEmptyTableVal()
check:
tomlRef.kind == TomlValueKind.Table

suite "bug fixes":
test "issue-45":
check $("some_float = 0.123".parseString()["some_float"].getFloat()) == "0.123"

0 comments on commit 3e4c2da

Please sign in to comment.