]> gitweb.factorcode.org Git - factor.git/commitdiff
formatting: fix bug when using %e and the number rounds up in magnitude
authorJon Harper <jon.harper87@gmail.com>
Sun, 9 Apr 2017 18:29:11 +0000 (20:29 +0200)
committerJohn Benediktsson <mrjbq7@gmail.com>
Thu, 8 Jun 2017 18:23:38 +0000 (11:23 -0700)
99/10 0 format-scientific-simple was outputting 1.0e0 because
the mantissa was rounded up, so it had one extra character, and
the exponent was wrong.

basis/formatting/formatting-tests.factor
basis/formatting/formatting.factor

index 710347ef3ebed370b552f62cd057f8dbfef69881..957eb20df731892196a308db768fe0ee70e14c5d 100755 (executable)
@@ -112,6 +112,9 @@ IN: formatting.tests
 { "9.88e+417" } [ 987654321098765432 10 400 ^ * "%.2e" sprintf ] unit-test
 { "9.9e+417" } [ 987654321098765432 10 400 ^ * "%.1e" sprintf ] unit-test
 { "1e+418" } [ 987654321098765432 10 400 ^ * "%.0e" sprintf ] unit-test
+{ "9e+417" } [ 937654321098765432 10 400 ^ * "%.0e" sprintf ] unit-test
+{ "1.0e+418" } [ 997654321098765432 10 400 ^ * "%.1e" sprintf ] unit-test
+{ "1.00e+418" } [ 999654321098765432 10 400 ^ * "%.2e" sprintf ] unit-test
 
 { "1.5625" } [ 1.5625 "%d" sprintf ] unit-test
 { "1.9p0" } [ 1.5625 "%x" sprintf ] unit-test
index ef0a2ec3b9cd89ee4af6a35ed5f4636d50960d9f..7cad3b94480fc65460e798cde6a2b95b07f63281 100644 (file)
@@ -37,12 +37,15 @@ IN: formatting
         [ cut* ] tri [ "." glue ] unless-empty
     ] curry keep neg? [ CHAR: - prefix ] when ;
 
-: format-scientific-mantissa ( x log10x digits -- string )
-    swap - 10^ * round-to-even >integer
-    number>string 1 cut [ "." glue ] unless-empty ;
-
-: format-scientific-exponent ( log10x -- string )
-    number>string 2 CHAR: 0 pad-head
+: format-scientific-mantissa ( x log10x digits -- string rounded-up? )
+    [ swap - 10^ * round-to-even >integer number>string ] keep
+    over length 1 - < [
+        [ but-last >string ] when ! 9.9 rounded to 1e+01
+        1 cut [ "." glue ] unless-empty
+    ] keep ;
+
+: format-scientific-exponent ( rounded-up? log10x -- string )
+    swap [ 1 + ] when number>string 2 CHAR: 0 pad-head
     dup CHAR: - swap index "e" "e+" ? prepend ;
 
 : format-scientific-simple ( x digits -- string )