mirror of
https://github.com/nim-lang/Nim.git
synced 2025-12-28 17:04:41 +00:00
fix strformat zeropadding for floats (#7934)
This commit is contained in:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user