number.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /**
  2. * 保留x位小数
  3. */
  4. export function toPrecision(num, precision) {
  5. var result = Math.pow(10, precision);
  6. // eslint-disable-next-line
  7. return ~~(num * result) / result;
  8. }
  9. /**
  10. * 千分位
  11. * 100000 -> 10,000
  12. */
  13. export function toThousands(num) {
  14. return num.toLocaleString();
  15. }
  16. /**
  17. * 获得数字科学计数
  18. * 1000000 = 1e6
  19. */
  20. export function toScientificNotation(num) {
  21. return num.toExponential();
  22. }
  23. /**
  24. * 用k的方式表达
  25. * 1234 -> 1K
  26. * 12345 -> 12K
  27. */
  28. export function toKNotation(num, precision) {
  29. if (precision === void 0) { precision = 0; }
  30. if (Math.abs(num) < 1000)
  31. return String(num);
  32. return "".concat(toPrecision(num / 1000, precision).toLocaleString(), "K");
  33. }
  34. // Condition if x is smaller than zero.
  35. export var ifNegative = function (x, a, b) { return (x < 0 && Number.isFinite(x) ? a : b); };
  36. // Condition if x is greater than zero.
  37. export var ifPositive = function (x, a, b) { return (x > 0 && Number.isFinite(x) ? a : b); };
  38. // Calculate the result of a * b.
  39. export var multi = function (a, b) { return a * b; };
  40. // Calculate the result of (a + b) / 2.
  41. export var mid = function (a, b) { return a / 2 + (b || 0) / 2; };
  42. //# sourceMappingURL=number.js.map