math.ts 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 = (num: number, length: number, decimal: number): number => {
  8. let value;
  9. let pre = 1;
  10. if (length === 0) return num;
  11. if (num < 0) pre = -1; // 负数的时候先变成正数
  12. num *= pre;
  13. const n = 10 ** length;
  14. value = Math.round(num * n);
  15. if (length <= decimal) {
  16. return (value / n) * pre;
  17. }
  18. value = Math.round(value / 10 ** (length - decimal));
  19. return (value / 10 ** decimal) * pre;
  20. };
  21. // 4舍5入
  22. export const roundForObj = (obj: string | number | undefined | null, decimal: number): number => {
  23. let value;
  24. if (obj === undefined || obj === null || isNaN(obj as number)) return 0;
  25. const length = 10;
  26. if (obj === +obj) {
  27. value = innerRound(obj, length, decimal);
  28. } else {
  29. value = innerRound(Number(obj), length, decimal);
  30. }
  31. return value;
  32. };
  33. export const roundToString = (obj: string | number, decimal: number): string => {
  34. const value = roundForObj(obj, decimal);
  35. return value.toFixed(decimal);
  36. };
  37. const getTimesFromStr = (str: string) => {
  38. const reg = new RegExp('^[0-9]+');
  39. if (str && reg.test(str)) {
  40. const arr: any = str.match(reg);
  41. return parseInt(arr[0], 10);
  42. }
  43. return 1;
  44. };
  45. // 取单位前的数字,并转换成整数
  46. export const getNumberFromUnit = (unit: string): number => {
  47. if (unit.indexOf('·') !== -1) {
  48. // 处理单位为 100m2·10天 的情况
  49. const strArr = unit.split('·');
  50. let time = 1;
  51. for (const s of strArr) {
  52. time *= getTimesFromStr(s);
  53. }
  54. return time;
  55. }
  56. return getTimesFromStr(unit);
  57. };