fix strformat zeropadding for floats (#7934)
This commit is contained in:
parent
b4626a220b
commit
07ff9940f4
2 changed files with 30 additions and 3 deletions
|
|
@ -524,8 +524,26 @@ proc format*(value: SomeFloat; specifier: string; res: var string) =
|
||||||
" of 'e', 'E', 'f', 'F', 'g', 'G' but got: " & spec.typ)
|
" of 'e', 'E', 'f', 'F', 'g', 'G' but got: " & spec.typ)
|
||||||
|
|
||||||
var f = formatBiggestFloat(value, fmode, spec.precision)
|
var f = formatBiggestFloat(value, fmode, spec.precision)
|
||||||
if value >= 0.0 and spec.sign != '-':
|
var sign = false
|
||||||
|
if value >= 0.0:
|
||||||
|
if spec.sign != '-':
|
||||||
f = spec.sign & f
|
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:
|
# the default for numbers is right-alignment:
|
||||||
let align = if spec.align == '\0': '>' else: spec.align
|
let align = if spec.align == '\0': '>' else: spec.align
|
||||||
let result = alignString(f, spec.minimumWidth,
|
let result = alignString(f, spec.minimumWidth,
|
||||||
|
|
|
||||||
|
|
@ -11,3 +11,12 @@ proc `$`(o: Obj): string = "foobar"
|
||||||
var o: Obj
|
var o: Obj
|
||||||
doAssert fmt"{o}" == "foobar"
|
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
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue