math.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /* eslint-disable no-param-reassign */
  2. /* eslint-disable no-restricted-globals */
  3. // 判断传入的是否是数字或者可转为数字的字符串
  4. export const isNumber = (value: string | number): boolean => {
  5. return /^(-|\+)?\d+(\.\d+)?$/.test(value as string);
  6. };
  7. export const innerRound = (
  8. num: number,
  9. length: number,
  10. decimal: number
  11. ): number => {
  12. let value;
  13. let pre = 1;
  14. if (length === 0) return num;
  15. if (num < 0) pre = -1; // 负数的时候先变成正数
  16. num *= pre;
  17. const n = 10 ** length;
  18. value = Math.round(num * n);
  19. if (length <= decimal) {
  20. return (value / n) * pre;
  21. }
  22. value = Math.round(value / 10 ** (length - decimal));
  23. return (value / 10 ** decimal) * pre;
  24. };
  25. // 4舍5入
  26. export const roundForObj = (
  27. obj: string | number | undefined | null,
  28. decimal: number
  29. ): number => {
  30. let value;
  31. if (obj === undefined || obj === null || isNaN(obj as number)) return 0;
  32. const length = 10;
  33. if (obj === +obj) {
  34. value = innerRound(obj, length, decimal);
  35. } else {
  36. value = innerRound(Number(obj), length, decimal);
  37. }
  38. return value;
  39. };
  40. export const roundToString = (
  41. obj: string | number,
  42. decimal: number
  43. ): string => {
  44. const value = roundForObj(obj, decimal);
  45. return value.toFixed(decimal);
  46. };
  47. // 取单位前的数字,并转换成整数
  48. export const getNumberFromUnit = (unit: string): number => {
  49. const reg = new RegExp('^[0-9]+');
  50. if (unit && reg.test(unit)) {
  51. const arr: any = unit.match(reg);
  52. return parseInt(arr[0], 10);
  53. }
  54. return 1;
  55. };