UNPKG

fenzhi-utils

Version:

分值前端项目的js函数库

26 lines (25 loc) 1 kB
/** * 将传入的数字乘以100并保留指定位数的小数,如果无法转换为数字则返回空字符串。 * @param {number} data 要转换的百分数 * @param {number} num 保留几位小数 * @returns {string} 返回转换后的百分数 */ /** test('CustomConverPercent', () => { expect(CustomConverPercent(0.123456)).toBe('12.35') expect(CustomConverPercent(0.123456, 3)).toBe('12.346') expect(CustomConverPercent('0.123456')).toBe('12.35') expect(CustomConverPercent('0.123456', 3)).toBe('12.346') expect(CustomConverPercent('')).toBe('') expect(CustomConverPercent(null)).toBe('') expect(CustomConverPercent(undefined)).toBe('') expect(CustomConverPercent(Infinity)).toBe('') }) */ export function CustomConverPercent(data, num = 2) { data = parseFloat(data); // 如果不能强制转换为数字 比如:null undefined ''等 则返回 '' if (isNaN(data) || data === Infinity) return ''; data *= 100; return data.toFixed(num); }