summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorskilchen <skilchen@users.noreply.github.com>2018-06-02 04:23:50 +0200
committerVarriount <Varriount@users.noreply.github.com>2018-06-01 22:23:50 -0400
commit07ff9940f4a990b57cfaa3ad274c7bcff46356ff (patch)
treec9c0bd539ab5c1450cfc55289bc097ab970c0520
parentb4626a220b2de0fee7360672915332c402bf9dc7 (diff)
downloadNim-07ff9940f4a990b57cfaa3ad274c7bcff46356ff.tar.gz
fix strformat zeropadding for floats (#7934)
-rw-r--r--lib/pure/strformat.nim22
-rw-r--r--tests/stdlib/tstrformat.nim11
2 files changed, 30 insertions, 3 deletions
diff --git a/lib/pure/strformat.nim b/lib/pure/strformat.nim
index a8b128460..12a102c9f 100644
--- a/lib/pure/strformat.nim
+++ b/lib/pure/strformat.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,
diff --git a/tests/stdlib/tstrformat.nim b/tests/stdlib/tstrformat.nim
index 4e5c614a7..b4cbd41e0 100644
--- a/tests/stdlib/tstrformat.nim
+++ b/tests/stdlib/tstrformat.nim
@@ -10,4 +10,13 @@ proc `$`(o: Obj): string = "foobar"
 
 var o: Obj
 doAssert fmt"{o}" == "foobar"
-doAssert fmt"{o:10}" == "foobar    "
\ No newline at end of file
+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