Skip to content

Commit 230692a

Browse files
skilchenVarriount
authored andcommitted
Fix strformat neg zero (#7954)
* fix strformat handling of neg zero with sign * better tests for neg zero with sign * use inplace insertion of the sign as suggested by Varriount
1 parent fd102f3 commit 230692a

File tree

2 files changed

+14
-1
lines changed

2 files changed

+14
-1
lines changed

lib/pure/strformat.nim

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -527,8 +527,13 @@ proc format*(value: SomeFloat; specifier: string; res: var string) =
527527
var sign = false
528528
if value >= 0.0:
529529
if spec.sign != '-':
530-
f = spec.sign & f
531530
sign = true
531+
if value == 0.0:
532+
if 1.0 / value == Inf:
533+
# only insert the sign if value != negZero
534+
f.insert($spec.sign, 0)
535+
else:
536+
f.insert($spec.sign, 0)
532537
else:
533538
sign = true
534539

tests/stdlib/tstrformat.nim

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,3 +46,11 @@ doAssert fmt"{-1.5:0>8}" == "0000-1.5" # even that does not work for negative fl
4646
doAssert fmt"{-1.5:08}" == "-00001.5" # works
4747
doAssert fmt"{1.5:+08}" == "+00001.5" # works
4848
doAssert fmt"{1.5: 08}" == " 00001.5" # works
49+
50+
# only add explicitly requested sign if value != -0.0 (neg zero)
51+
doAssert fmt"{-0.0:g}" == "-0"
52+
doassert fmt"{-0.0:+g}" == "-0"
53+
doassert fmt"{-0.0: g}" == "-0"
54+
doAssert fmt"{0.0:g}" == "0"
55+
doAssert fmt"{0.0:+g}" == "+0"
56+
doAssert fmt"{0.0: g}" == " 0"

0 commit comments

Comments
 (0)