NumberPrototype.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. using System;
  2. using System.Globalization;
  3. using System.Text;
  4. using Jint.Native.Number.Dtoa;
  5. using Jint.Runtime;
  6. using Jint.Runtime.Interop;
  7. namespace Jint.Native.Number
  8. {
  9. /// <summary>
  10. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.7.4
  11. /// </summary>
  12. public sealed class NumberPrototype : NumberInstance
  13. {
  14. private static readonly char[] _numberSeparators = {'.', 'e'};
  15. private NumberPrototype(Engine engine)
  16. : base(engine)
  17. {
  18. }
  19. public static NumberPrototype CreatePrototypeObject(Engine engine, NumberConstructor numberConstructor)
  20. {
  21. var obj = new NumberPrototype(engine)
  22. {
  23. Prototype = engine.Object.PrototypeObject,
  24. NumberData = JsNumber.Create(0),
  25. Extensible = true
  26. };
  27. obj.FastAddProperty("constructor", numberConstructor, true, false, true);
  28. return obj;
  29. }
  30. public void Configure()
  31. {
  32. FastAddProperty("toString", new ClrFunctionInstance(Engine, ToNumberString), true, false, true);
  33. FastAddProperty("toLocaleString", new ClrFunctionInstance(Engine, ToLocaleString), true, false, true);
  34. FastAddProperty("valueOf", new ClrFunctionInstance(Engine, ValueOf), true, false, true);
  35. FastAddProperty("toFixed", new ClrFunctionInstance(Engine, ToFixed, 1), true, false, true);
  36. FastAddProperty("toExponential", new ClrFunctionInstance(Engine, ToExponential), true, false, true);
  37. FastAddProperty("toPrecision", new ClrFunctionInstance(Engine, ToPrecision), true, false, true);
  38. }
  39. private JsValue ToLocaleString(JsValue thisObject, JsValue[] arguments)
  40. {
  41. if (!thisObject.IsNumber() && ReferenceEquals(thisObject.TryCast<NumberInstance>(), null))
  42. {
  43. ExceptionHelper.ThrowTypeError(Engine);
  44. }
  45. var m = TypeConverter.ToNumber(thisObject);
  46. if (double.IsNaN(m))
  47. {
  48. return "NaN";
  49. }
  50. if (m == 0)
  51. {
  52. return "0";
  53. }
  54. if (m < 0)
  55. {
  56. return "-" + ToLocaleString(-m, arguments);
  57. }
  58. if (double.IsPositiveInfinity(m) || m >= double.MaxValue)
  59. {
  60. return "Infinity";
  61. }
  62. if (double.IsNegativeInfinity(m) || m <= -double.MaxValue)
  63. {
  64. return "-Infinity";
  65. }
  66. return m.ToString("n", Engine.Options._Culture);
  67. }
  68. private JsValue ValueOf(JsValue thisObj, JsValue[] arguments)
  69. {
  70. var number = thisObj.TryCast<NumberInstance>();
  71. if (ReferenceEquals(number, null))
  72. {
  73. ExceptionHelper.ThrowTypeError(Engine);
  74. }
  75. return number.NumberData;
  76. }
  77. private const double Ten21 = 1e21;
  78. private JsValue ToFixed(JsValue thisObj, JsValue[] arguments)
  79. {
  80. var f = (int)TypeConverter.ToInteger(arguments.At(0, 0));
  81. if (f < 0 || f > 20)
  82. {
  83. ExceptionHelper.ThrowRangeError(_engine, "fractionDigits argument must be between 0 and 20");
  84. }
  85. var x = TypeConverter.ToNumber(thisObj);
  86. if (double.IsNaN(x))
  87. {
  88. return "NaN";
  89. }
  90. if (x >= Ten21)
  91. {
  92. return ToNumberString(x);
  93. }
  94. return x.ToString("f" + f, CultureInfo.InvariantCulture);
  95. }
  96. private JsValue ToExponential(JsValue thisObj, JsValue[] arguments)
  97. {
  98. var f = (int)TypeConverter.ToInteger(arguments.At(0, 16));
  99. if (f < 0 || f > 20)
  100. {
  101. ExceptionHelper.ThrowRangeError(_engine, "fractionDigits argument must be between 0 and 20");
  102. }
  103. var x = TypeConverter.ToNumber(thisObj);
  104. if (double.IsNaN(x))
  105. {
  106. return "NaN";
  107. }
  108. string format = string.Concat("#.", new string('0', f), "e+0");
  109. return x.ToString(format, CultureInfo.InvariantCulture);
  110. }
  111. private JsValue ToPrecision(JsValue thisObj, JsValue[] arguments)
  112. {
  113. var x = TypeConverter.ToNumber(thisObj);
  114. if (arguments.At(0).IsUndefined())
  115. {
  116. return TypeConverter.ToString(x);
  117. }
  118. var p = TypeConverter.ToInteger(arguments.At(0));
  119. if (double.IsInfinity(x) || double.IsNaN(x))
  120. {
  121. return TypeConverter.ToString(x);
  122. }
  123. if (p < 1 || p > 21)
  124. {
  125. ExceptionHelper.ThrowRangeError(_engine, "precision must be between 1 and 21");
  126. }
  127. // Get the number of decimals
  128. string str = x.ToString("e23", CultureInfo.InvariantCulture);
  129. int decimals = str.IndexOfAny(_numberSeparators);
  130. decimals = decimals == -1 ? str.Length : decimals;
  131. p -= decimals;
  132. p = p < 1 ? 1 : p;
  133. return x.ToString("f" + p, CultureInfo.InvariantCulture);
  134. }
  135. private JsValue ToNumberString(JsValue thisObject, JsValue[] arguments)
  136. {
  137. if (!thisObject.IsNumber() && (ReferenceEquals(thisObject.TryCast<NumberInstance>(), null)))
  138. {
  139. ExceptionHelper.ThrowTypeError(_engine);
  140. }
  141. var radix = arguments.At(0).IsUndefined()
  142. ? 10
  143. : (int) TypeConverter.ToInteger(arguments.At(0));
  144. if (radix < 2 || radix > 36)
  145. {
  146. ExceptionHelper.ThrowRangeError(_engine, "radix must be between 2 and 36");
  147. }
  148. var x = TypeConverter.ToNumber(thisObject);
  149. if (double.IsNaN(x))
  150. {
  151. return "NaN";
  152. }
  153. if (x == 0)
  154. {
  155. return "0";
  156. }
  157. if (double.IsPositiveInfinity(x) || x >= double.MaxValue)
  158. {
  159. return "Infinity";
  160. }
  161. if (x < 0)
  162. {
  163. return "-" + ToNumberString(-x, arguments);
  164. }
  165. if (radix == 10)
  166. {
  167. return ToNumberString(x);
  168. }
  169. var integer = (long) x;
  170. var fraction = x - integer;
  171. string result = ToBase(integer, radix);
  172. if (fraction != 0)
  173. {
  174. result += "." + ToFractionBase(fraction, radix);
  175. }
  176. return result;
  177. }
  178. public static string ToBase(long n, int radix)
  179. {
  180. const string digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  181. if (n == 0)
  182. {
  183. return "0";
  184. }
  185. var result = new StringBuilder();
  186. while (n > 0)
  187. {
  188. var digit = (int)(n % radix);
  189. n = n / radix;
  190. result.Insert(0, digits[digit]);
  191. }
  192. return result.ToString();
  193. }
  194. public static string ToFractionBase(double n, int radix)
  195. {
  196. // based on the repeated multiplication method
  197. // http://www.mathpath.org/concepts/Num/frac.htm
  198. const string digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  199. if (n == 0)
  200. {
  201. return "0";
  202. }
  203. var result = new StringBuilder();
  204. while (n > 0 && result.Length < 50) // arbitrary limit
  205. {
  206. var c = n*radix;
  207. var d = (int) c;
  208. n = c - d;
  209. result.Append(digits[d]);
  210. }
  211. return result.ToString();
  212. }
  213. public static string ToNumberString(double m)
  214. {
  215. if (double.IsNaN(m))
  216. {
  217. return "NaN";
  218. }
  219. if (m == 0)
  220. {
  221. return "0";
  222. }
  223. if (double.IsPositiveInfinity(m) || m >= double.MaxValue)
  224. {
  225. return "Infinity";
  226. }
  227. if (m < 0)
  228. {
  229. return "-" + ToNumberString(-m);
  230. }
  231. // V8 FastDtoa can't convert all numbers, so try it first but
  232. // fall back to old DToA in case it fails
  233. var result = FastDtoa.NumberToString(m);
  234. if (result != null)
  235. {
  236. return result;
  237. }
  238. // s is all digits (significand)
  239. // k number of digits of s
  240. // n total of digits in fraction s*10^n-k=m
  241. // 123.4 s=1234, k=4, n=3
  242. // 1234000 s = 1234, k=4, n=7
  243. string s = null;
  244. var rFormat = m.ToString("r", CultureInfo.InvariantCulture);
  245. if (rFormat.IndexOf("e", StringComparison.OrdinalIgnoreCase) == -1)
  246. {
  247. s = rFormat.Replace(".", "").TrimStart('0').TrimEnd('0');
  248. }
  249. const string format = "0.00000000000000000e0";
  250. var parts = m.ToString(format, CultureInfo.InvariantCulture).Split('e');
  251. if (s == null)
  252. {
  253. s = parts[0].TrimEnd('0').Replace(".", "");
  254. }
  255. var n = int.Parse(parts[1]) + 1;
  256. var k = s.Length;
  257. if (k <= n && n <= 21)
  258. {
  259. return s + new string('0', n - k);
  260. }
  261. if (0 < n && n <= 21)
  262. {
  263. return s.Substring(0, n) + '.' + s.Substring(n);
  264. }
  265. if (-6 < n && n <= 0)
  266. {
  267. return "0." + new string('0', -n) + s;
  268. }
  269. if (k == 1)
  270. {
  271. return s + "e" + (n - 1 < 0 ? "-" : "+") + System.Math.Abs(n - 1);
  272. }
  273. return s.Substring(0, 1) + "." + s.Substring(1) + "e" + (n - 1 < 0 ? "-" : "+") + System.Math.Abs(n - 1);
  274. }
  275. }
  276. }