Skip to content

Commit 07ff994

Browse files
skilchenVarriount
authored andcommitted
fix strformat zeropadding for floats (#7934)
1 parent b4626a2 commit 07ff994

File tree

2 files changed

+30
-3
lines changed

2 files changed

+30
-3
lines changed

lib/pure/strformat.nim

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -524,8 +524,26 @@ proc format*(value: SomeFloat; specifier: string; res: var string) =
524524
" of 'e', 'E', 'f', 'F', 'g', 'G' but got: " & spec.typ)
525525

526526
var f = formatBiggestFloat(value, fmode, spec.precision)
527-
if value >= 0.0 and spec.sign != '-':
528-
f = spec.sign & f
527+
var sign = false
528+
if value >= 0.0:
529+
if spec.sign != '-':
530+
f = spec.sign & f
531+
sign = true
532+
else:
533+
sign = true
534+
535+
if spec.padWithZero:
536+
var sign_str = ""
537+
if sign:
538+
sign_str = $f[0]
539+
f = f[1..^1]
540+
541+
let toFill = spec.minimumWidth - f.len - ord(sign)
542+
if toFill > 0:
543+
f = repeat('0', toFill) & f
544+
if sign:
545+
f = sign_str & f
546+
529547
# the default for numbers is right-alignment:
530548
let align = if spec.align == '\0': '>' else: spec.align
531549
let result = alignString(f, spec.minimumWidth,

tests/stdlib/tstrformat.nim

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,13 @@ proc `$`(o: Obj): string = "foobar"
1010

1111
var o: Obj
1212
doAssert fmt"{o}" == "foobar"
13-
doAssert fmt"{o:10}" == "foobar "
13+
doAssert fmt"{o:10}" == "foobar "
14+
15+
# see issue #7932
16+
doAssert fmt"{15:08}" == "00000015" # int, works
17+
doAssert fmt"{1.5:08}" == "000001.5" # float, works
18+
doAssert fmt"{1.5:0>8}" == "000001.5" # workaround using fill char works for positive floats
19+
doAssert fmt"{-1.5:0>8}" == "0000-1.5" # even that does not work for negative floats
20+
doAssert fmt"{-1.5:08}" == "-00001.5" # works
21+
doAssert fmt"{1.5:+08}" == "+00001.5" # works
22+
doAssert fmt"{1.5: 08}" == " 00001.5" # works

0 commit comments

Comments
 (0)