Convert.java 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package gnu.ecmascript;
  2. public class Convert
  3. {
  4. public static double toNumber(Object x)
  5. {
  6. if (x instanceof java.lang.Number)
  7. return ((java.lang.Number)x).doubleValue();
  8. //if (x == ECMAScript.UNDEFINED) return Double.NaN;
  9. // if (x == ECMAScript.NULL) return 0;
  10. if (x instanceof Boolean)
  11. return ((Boolean)x).booleanValue() ? 1 : 0;
  12. if (x instanceof String)
  13. {
  14. try
  15. {
  16. // FIXME - is Java grammar correct for ECMAScript?
  17. return Double.valueOf((String)x).doubleValue();
  18. }
  19. catch (NumberFormatException ex)
  20. {
  21. return Double.NaN;
  22. }
  23. }
  24. // if (x instanceof JSObject) { FIXME }
  25. return Double.NaN;
  26. }
  27. public static double toInteger(double x)
  28. {
  29. if (Double.isNaN(x))
  30. return 0.0;
  31. return x < 0.0 ? Math.ceil (x) : Math.floor (x);
  32. }
  33. public static double toInteger(Object x)
  34. {
  35. return toInteger(toNumber(x));
  36. }
  37. public int toInt32 (double x)
  38. {
  39. if (Double.isNaN(x) || Double.isInfinite(x))
  40. return 0;
  41. // FIXME - does not handle overflow correctly!
  42. return (int) x;
  43. }
  44. public int toInt32 (Object x)
  45. {
  46. return toInt32(toNumber(x));
  47. }
  48. }