2
0
Эх сурвалжийг харах

Add decimal support under type conversion (#1342)

Marko Lahma 2 жил өмнө
parent
commit
8301536bbb

+ 14 - 0
Jint.Tests/Runtime/InteropTests.NewtonsoftJson.cs

@@ -1,3 +1,4 @@
+using Jint.Native;
 using Jint.Native.Date;
 using Jint.Runtime;
 using Newtonsoft.Json.Linq;
@@ -102,5 +103,18 @@ namespace Jint.Tests.Runtime
 
             Assert.Equal("[{\"Text\":\"Text1\",\"Value\":1},{\"Text\":\"Text2\",\"Value\":2,\"Null\":null,\"Date\":\"2015-06-25T00:00:00.000Z\"}]", result);
         }
+        
+        [Fact]
+        public void DecimalsShouldBeHandledFromJObjects()
+        {
+            var test = JObject.FromObject(new
+            {
+                DecimalValue = 123.456m
+            });
+            _engine.SetValue("test", test);
+            var fromInterop = _engine.Evaluate("test.DecimalValue");
+            var number = Assert.IsType<JsNumber>(fromInterop);
+            Assert.Equal(123.456d, number.AsNumber());
+        }
     }
 }

+ 10 - 10
Jint/Native/JsNumber.cs

@@ -78,18 +78,18 @@ namespace Jint.Native
         internal static JsNumber Create(object value)
         {
             var underlyingType = System.Type.GetTypeCode(Enum.GetUnderlyingType(value.GetType()));
-            switch (underlyingType)
+            return underlyingType switch
             {
-                case TypeCode.Int64:
-                    return Create(Convert.ToInt64(value));
-
-                case TypeCode.UInt32:
-                case TypeCode.UInt64:
-                    return Create(Convert.ToUInt64(value));
+                TypeCode.Int64 => Create(Convert.ToInt64(value)),
+                TypeCode.UInt32 => Create(Convert.ToUInt64(value)),
+                TypeCode.UInt64 => Create(Convert.ToUInt64(value)),
+                _ => Create(Convert.ToInt32(value))
+            };
+        }
 
-                default:
-                    return Create(Convert.ToInt32(value));
-            }
+        public static JsNumber Create(decimal value)
+        {
+            return Create((double) value);
         }
 
         [MethodImpl(MethodImplOptions.AggressiveInlining)]