index.ts 724 B

12345678910111213141516171819202122232425
  1. /* eslint-disable no-restricted-globals */
  2. // 判断传入的是否是数字或者可转为数字的字符串
  3. export const isNumber = (value: string | number) => {
  4. return /^(-|\+)?\d+(\.\d+)?$/.test(value as string);
  5. };
  6. export const roundForObj = (obj: string | number, decimal: number): number => {
  7. let value;
  8. if (obj === undefined || obj === null || isNaN(obj as number)) return 0;
  9. const n = 10 ** decimal;
  10. if (obj === +obj) {
  11. value = Math.round(obj * n) / n;
  12. } else {
  13. value = Math.round(Number(obj) * n) / n;
  14. }
  15. return value;
  16. };
  17. export const roundToString = (
  18. obj: string | number,
  19. decimal: number
  20. ): string => {
  21. const value = roundForObj(obj, decimal);
  22. return value.toFixed(decimal);
  23. };