Browse Source

Fixing toFixed implementation

#158
Sebastien Ros 10 years ago
parent
commit
7a19308dee
2 changed files with 24 additions and 10 deletions
  1. 23 1
      Jint.Tests/Runtime/EngineTests.cs
  2. 1 9
      Jint/Native/Number/NumberPrototype.cs

+ 23 - 1
Jint.Tests/Runtime/EngineTests.cs

@@ -1160,6 +1160,28 @@ namespace Jint.Tests.Runtime
             RunTest(@"
                 assert(true === isNaN());
             ");
-        }    
+        }
+
+        [Theory]
+        [InlineData(4d, 0, "4")]
+        [InlineData(4d, 1, "4.0")]
+        [InlineData(4d, 2, "4.00")]
+        [InlineData(28.995, 2, "29.00")]
+        [InlineData(-28.995, 2, "-29.00")]
+        [InlineData(-28.495, 2, "-28.50")]
+        [InlineData(-28.445, 2, "-28.45")]
+        [InlineData(28.445, 2, "28.45")]
+        [InlineData(10.995, 0, "11")]
+        public void ShouldRoundToFixedDecimal(double number, int fractionDigits, string result)
+        {
+            var engine = new Engine();
+            var value = engine.Execute(
+                String.Format("new Number({0}).toFixed({1})",
+                    number.ToString(CultureInfo.InvariantCulture),
+                    fractionDigits.ToString(CultureInfo.InvariantCulture)))
+                .GetCompletionValue().ToObject();
+
+            Assert.Equal(value, result);
+        }
     }
 }

+ 1 - 9
Jint/Native/Number/NumberPrototype.cs

@@ -108,16 +108,8 @@ namespace Jint.Native.Number
             {
                 return ToNumberString(x);
             }
-    
-            var l = (long) x; // extract integer part
 
-            if (f == 0)
-            {
-                return l.ToString(CultureInfo.InvariantCulture);
-            }
-
-            var d = x - l;
-            return l.ToString(CultureInfo.InvariantCulture) + d.ToString("." + new string('0', f), CultureInfo.InvariantCulture);
+            return x.ToString("f" + f, CultureInfo.InvariantCulture);
         }
 
         private JsValue ToExponential(JsValue thisObj, JsValue[] arguments)