Permalink
Browse files

fix strformat zeropadding for floats (#7934)

  • Loading branch information...
skilchen authored and Varriount committed Jun 2, 2018
1 parent b4626a2 commit 07ff9940f4a990b57cfaa3ad274c7bcff46356ff
Showing with 30 additions and 3 deletions.
  1. +20 −2 lib/pure/strformat.nim
  2. +10 −1 tests/stdlib/tstrformat.nim
@@ -524,8 +524,26 @@ proc format*(value: SomeFloat; specifier: string; res: var string) =
" of 'e', 'E', 'f', 'F', 'g', 'G' but got: " & spec.typ)

var f = formatBiggestFloat(value, fmode, spec.precision)
if value >= 0.0 and spec.sign != '-':
f = spec.sign & f
var sign = false
if value >= 0.0:
if spec.sign != '-':
f = spec.sign & f
sign = true
else:
sign = true

if spec.padWithZero:
var sign_str = ""
if sign:
sign_str = $f[0]
f = f[1..^1]

let toFill = spec.minimumWidth - f.len - ord(sign)
if toFill > 0:
f = repeat('0', toFill) & f
if sign:
f = sign_str & f

# the default for numbers is right-alignment:
let align = if spec.align == '\0': '>' else: spec.align
let result = alignString(f, spec.minimumWidth,
@@ -10,4 +10,13 @@ proc `$`(o: Obj): string = "foobar"

var o: Obj
doAssert fmt"{o}" == "foobar"
doAssert fmt"{o:10}" == "foobar "
doAssert fmt"{o:10}" == "foobar "

# see issue #7932
doAssert fmt"{15:08}" == "00000015" # int, works
doAssert fmt"{1.5:08}" == "000001.5" # float, works
doAssert fmt"{1.5:0>8}" == "000001.5" # workaround using fill char works for positive floats
doAssert fmt"{-1.5:0>8}" == "0000-1.5" # even that does not work for negative floats
doAssert fmt"{-1.5:08}" == "-00001.5" # works
doAssert fmt"{1.5:+08}" == "+00001.5" # works
doAssert fmt"{1.5: 08}" == " 00001.5" # works

0 comments on commit 07ff994

Please sign in to comment.