You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.1 KiB

4 years ago
  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. }