From 0e8a4ba4ee698bde17fc8357700fcdd0af4ed815 Mon Sep 17 00:00:00 2001 From: skilchen Date: Thu, 31 May 2018 19:40:00 +0200 Subject: [PATCH 1/3] fix strformat handling of neg zero with sign --- lib/pure/strformat.nim | 8 +++++++- tests/stdlib/tstrformat.nim | 4 +++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/pure/strformat.nim b/lib/pure/strformat.nim index a8b128460782..87ee7fddb858 100644 --- a/lib/pure/strformat.nim +++ b/lib/pure/strformat.nim @@ -525,7 +525,13 @@ proc format*(value: SomeFloat; specifier: string; res: var string) = var f = formatBiggestFloat(value, fmode, spec.precision) if value >= 0.0 and spec.sign != '-': - f = spec.sign & f + if value == 0.0: + if 1.0 / value == Inf: + # only add the sign if value != negZero + f = spec.sign & f + else: + f = spec.sign & f + # the default for numbers is right-alignment: let align = if spec.align == '\0': '>' else: spec.align let result = alignString(f, spec.minimumWidth, diff --git a/tests/stdlib/tstrformat.nim b/tests/stdlib/tstrformat.nim index 4e5c614a7818..851328f62754 100644 --- a/tests/stdlib/tstrformat.nim +++ b/tests/stdlib/tstrformat.nim @@ -10,4 +10,6 @@ proc `$`(o: Obj): string = "foobar" var o: Obj doAssert fmt"{o}" == "foobar" -doAssert fmt"{o:10}" == "foobar " \ No newline at end of file +doAssert fmt"{o:10}" == "foobar " + +doAssert fmt"{-0.0:g}" == "-0" \ No newline at end of file From 9caefe1f362c1b08cc9a148a62a4e36ceaeebb20 Mon Sep 17 00:00:00 2001 From: skilchen Date: Thu, 31 May 2018 20:14:54 +0200 Subject: [PATCH 2/3] better tests for neg zero with sign --- tests/stdlib/tstrformat.nim | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/stdlib/tstrformat.nim b/tests/stdlib/tstrformat.nim index 851328f62754..e6ff12a1c867 100644 --- a/tests/stdlib/tstrformat.nim +++ b/tests/stdlib/tstrformat.nim @@ -12,4 +12,7 @@ var o: Obj doAssert fmt"{o}" == "foobar" doAssert fmt"{o:10}" == "foobar " -doAssert fmt"{-0.0:g}" == "-0" \ No newline at end of file +doAssert fmt"{-0.0:g}" == "-0" +doassert fmt"{-0.0:+g}" == "-0" +doAssert fmt"{0.0:g}" == "0" +doAssert fmt"{0.0:+g}" == "+0" \ No newline at end of file From a2a25286d1e510b491a45e41b93d07e273be4761 Mon Sep 17 00:00:00 2001 From: skilchen Date: Tue, 5 Jun 2018 02:01:59 +0200 Subject: [PATCH 3/3] use inplace insertion of the sign as suggested by Varriount --- lib/pure/strformat.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/pure/strformat.nim b/lib/pure/strformat.nim index 16c703bb70b3..36404cdf7ca1 100644 --- a/lib/pure/strformat.nim +++ b/lib/pure/strformat.nim @@ -530,10 +530,10 @@ proc format*(value: SomeFloat; specifier: string; res: var string) = sign = true if value == 0.0: if 1.0 / value == Inf: - # only add the sign if value != negZero - f = spec.sign & f + # only insert the sign if value != negZero + f.insert($spec.sign, 0) else: - f = spec.sign & f + f.insert($spec.sign, 0) else: sign = true