number.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. "use strict";
  2. exports.__esModule = true;
  3. exports.range = range;
  4. exports.formatNumber = formatNumber;
  5. exports.addNumber = addNumber;
  6. function range(num, min, max) {
  7. return Math.min(Math.max(num, min), max);
  8. }
  9. function trimExtraChar(value, _char, regExp) {
  10. var index = value.indexOf(_char);
  11. var prefix = '';
  12. if (index === -1) {
  13. return value;
  14. }
  15. if (_char === '-' && index !== 0) {
  16. return value.slice(0, index);
  17. }
  18. if (_char === '.' && value.match(/^(\.|-\.)/)) {
  19. prefix = index ? '-0' : '0';
  20. }
  21. return prefix + value.slice(0, index + 1) + value.slice(index).replace(regExp, '');
  22. }
  23. function formatNumber(value, allowDot, allowMinus) {
  24. if (allowDot === void 0) {
  25. allowDot = true;
  26. }
  27. if (allowMinus === void 0) {
  28. allowMinus = true;
  29. }
  30. if (allowDot) {
  31. value = trimExtraChar(value, '.', /\./g);
  32. } else {
  33. value = value.split('.')[0];
  34. }
  35. if (allowMinus) {
  36. value = trimExtraChar(value, '-', /-/g);
  37. } else {
  38. value = value.replace(/-/, '');
  39. }
  40. var regExp = allowDot ? /[^-0-9.]/g : /[^-0-9]/g;
  41. return value.replace(regExp, '');
  42. } // add num and avoid float number
  43. function addNumber(num1, num2) {
  44. var cardinal = Math.pow(10, 10);
  45. return Math.round((num1 + num2) * cardinal) / cardinal;
  46. }