index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. export default function parse(input) {
  2. input = input.toUpperCase();
  3. var splitIndex = input.indexOf("P");
  4. var mantissa, exponent;
  5. if (splitIndex !== -1) {
  6. mantissa = input.substring(0, splitIndex);
  7. exponent = parseInt(input.substring(splitIndex + 1));
  8. } else {
  9. mantissa = input;
  10. exponent = 0;
  11. }
  12. var dotIndex = mantissa.indexOf(".");
  13. if (dotIndex !== -1) {
  14. var integerPart = parseInt(mantissa.substring(0, dotIndex), 16);
  15. var sign = Math.sign(integerPart);
  16. integerPart = sign * integerPart;
  17. var fractionLength = mantissa.length - dotIndex - 1;
  18. var fractionalPart = parseInt(mantissa.substring(dotIndex + 1), 16);
  19. var fraction = fractionLength > 0 ? fractionalPart / Math.pow(16, fractionLength) : 0;
  20. if (sign === 0) {
  21. if (fraction === 0) {
  22. mantissa = sign;
  23. } else {
  24. if (Object.is(sign, -0)) {
  25. mantissa = -fraction;
  26. } else {
  27. mantissa = fraction;
  28. }
  29. }
  30. } else {
  31. mantissa = sign * (integerPart + fraction);
  32. }
  33. } else {
  34. mantissa = parseInt(mantissa, 16);
  35. }
  36. return mantissa * (splitIndex !== -1 ? Math.pow(2, exponent) : 1);
  37. }