consistent floating point output (#12219)

* unify float printing
* makes tests green
This commit is contained in:
Andreas Rumpf 2019-09-20 10:41:40 +02:00 • committed by GitHub
commit 7bc5bf8334
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 81 additions and 34 deletions

View file

@ -74,6 +74,15 @@ proc nimIntToStr(x: int): string {.compilerRtl.} =
result = newStringOfCap(sizeof(x)*4)
result.addInt x
proc addCstringN(result: var string, buf: cstring; buflen: int) =
# no nimvm support needed, so it doesn't need to be fast here either
let oldLen = result.len
let newLen = oldLen + buflen
result.setLen newLen
copyMem(result[oldLen].addr, buf, buflen)
import formatfloat
proc addFloat*(result: var string; x: float) =
## Converts float to its string representation and appends it to `result`.
##
@ -85,37 +94,9 @@ proc addFloat*(result: var string; x: float) =
when nimvm:
result.add $x
else:
var buf: array[0..64, char]
when defined(nimNoArrayToCstringConversion):
var n: int = c_sprintf(addr buf, "%.16g", x)
else:
var n: int = c_sprintf(buf, "%.16g", x)
var hasDot = false
for i in 0..n-1:
if buf[i] == ',':
buf[i] = '.'
hasDot = true
elif buf[i] in {'a'..'z', 'A'..'Z', '.'}:
hasDot = true
if not hasDot:
buf[n] = '.'
buf[n+1] = '0'
buf[n+2] = '\0'
# On Windows nice numbers like '1.#INF', '-1.#INF' or '1.#NAN'
# of '-1.#IND' are produced.
# We want to get rid of these here:
if buf[n-1] in {'n', 'N', 'D', 'd'}:
result.add "nan"
elif buf[n-1] == 'F':
if buf[0] == '-':
result.add "-inf"
else:
result.add "inf"
else:
var i = 0
while buf[i] != '\0':
result.add buf[i]
inc i
var buffer: array[65, char]
let n = writeFloatToBuffer(buffer, x)
result.addCstringN(cstring(buffer[0].addr), n)
proc add*(result: var string; x: float) {.deprecated:
"Deprecated since v0.20, use 'addFloat'".} =