Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix strformat zeropadding for floats #7934

Merged
merged 1 commit into from
Jun 2, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions lib/pure/strformat.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
11 changes: 10 additions & 1 deletion tests/stdlib/tstrformat.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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