| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- /* eslint-disable no-param-reassign */
- /* eslint-disable no-restricted-globals */
- // 判断传入的是否是数字或者可转为数字的字符串
- export const isNumber = (value: string | number): boolean => {
- return /^(-|\+)?\d+(\.\d+)?$/.test(value as string);
- };
- export const innerRound = (
- num: number,
- length: number,
- decimal: number
- ): number => {
- let value;
- let pre = 1;
- if (length === 0) return num;
- if (num < 0) pre = -1; // 负数的时候先变成正数
- num *= pre;
- const n = 10 ** length;
- value = Math.round(num * n);
- if (length <= decimal) {
- return (value / n) * pre;
- }
- value = Math.round(value / 10 ** (length - decimal));
- return (value / 10 ** decimal) * pre;
- };
- // 4舍5入
- export const roundForObj = (
- obj: string | number | undefined | null,
- decimal: number
- ): number => {
- let value;
- if (obj === undefined || obj === null || isNaN(obj as number)) return 0;
- const length = 10;
- if (obj === +obj) {
- value = innerRound(obj, length, decimal);
- } else {
- value = innerRound(Number(obj), length, decimal);
- }
- return value;
- };
- export const roundToString = (
- obj: string | number,
- decimal: number
- ): string => {
- const value = roundForObj(obj, decimal);
- return value.toFixed(decimal);
- };
- // 取单位前的数字,并转换成整数
- export const getNumberFromUnit = (unit: string): number => {
- const reg = new RegExp('^[0-9]+');
- if (unit && reg.test(unit)) {
- const arr: any = unit.match(reg);
- return parseInt(arr[0], 10);
- }
- return 1;
- };
|