forked from Taritsyn/JavaScriptEngineSwitcher
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumericHelpers.cs
More file actions
75 lines (67 loc) · 1.66 KB
/
NumericHelpers.cs
File metadata and controls
75 lines (67 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using System;
using JavaScriptEngineSwitcher.Core.Extensions;
namespace JavaScriptEngineSwitcher.ChakraCore.Helpers
{
/// <summary>
/// Numeric helpers
/// </summary>
internal static class NumericHelpers
{
private const double MAX_INTEGER_IN_DOUBLE = (1L << 53) - 1;
/// <summary>
/// Gets a value indicating whether the specified type is one of the numeric types
/// </summary>
/// <param name="type">The type</param>
/// <returns>true if the specified type is one of the numeric types; otherwise, false</returns>
public static bool IsNumericType(Type type)
{
TypeCode typeCode = type.GetTypeCode();
switch (typeCode)
{
case TypeCode.SByte:
case TypeCode.Byte:
case TypeCode.Int16:
case TypeCode.UInt16:
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Single:
case TypeCode.Double:
case TypeCode.Decimal:
return true;
default:
return false;
}
}
/// <summary>
/// Casts a double value to the correct type
/// </summary>
/// <param name="value">Double value</param>
/// <returns>Numeric value with the correct type</returns>
public static object CastDoubleValueToCorrectType(double value)
{
if (Math.Round(value) == value)
{
if (Math.Abs(value) <= MAX_INTEGER_IN_DOUBLE)
{
long longValue = Convert.ToInt64(value);
if (longValue >= int.MinValue && longValue <= int.MaxValue)
{
return (int)longValue;
}
return longValue;
}
}
else
{
float floatValue = Convert.ToSingle(value);
if (value == floatValue)
{
return floatValue;
}
}
return value;
}
}
}