/** * 获取目标类型的名称 0:人脸, 1:自行车, 2:巴士, 3:小汽车, 4:电动车|摩托车, 5:人体, 6:三轮车,7货车、8车牌、9推车,10鸟、11猫,12 狗,13老鼠 * @param objectType * @returns */ export const getObjectTypeName = (objectType: TObjectType) => { switch (objectType) { case 0: return "人脸"; case 1: return "自行车"; case 2: return "巴士"; case 3: return "小汽车"; case 4: return "电动车|摩托车"; case 5: return "人体"; case 6: return "三轮车"; case 7: return "货车"; case 8: return "车牌"; case 9: return "推车"; case 10: return "鸟"; case 11: return "猫"; case 12: return "狗"; case 13: return "老鼠"; default: return "--"; } } // 解决加减乘除中浮点数精度问题 /** * arg1 第一位数字 * arg2 第二位数字 * type 运算符类型 加add, 减reduce,乘ride,除except */ export const FloatPoint = (arg1: number, arg2: number, type: 'add' | 'reduce' | 'ride' | 'except') => { let r1: number = 0; let r2: number = 0; try { r1 = arg1.toString().split(".")[1].length; } catch (e) { r1 = 0; } try { r2 = arg2.toString().split(".")[1].length; } catch (e) { r2 = 0; } const c: number = Math.abs(r1 - r2); // 位数差的绝对值 const m: number = Math.pow(10, Math.max(r1, r2)); // 较大数的幂 if (c > 0) { // 位数相差 const cm: number = Math.pow(10, c); if (r1 > r2) { arg1 = Number(arg1.toString().replace(".", "")); // 转化成数字 arg2 = Number(arg2.toString().replace(".", "")) * cm; } else { arg1 = Number(arg1.toString().replace(".", "")) * cm; arg2 = Number(arg2.toString().replace(".", "")); } } else { // 位数相等 arg1 = Number(arg1.toString().replace(".", "")); arg2 = Number(arg2.toString().replace(".", "")); } let res: any = null; if (type === 'add') { res = (arg1 + arg2) / m; } else if (type === 'reduce') { res = (arg1 - arg2) / m; } else if (type === 'ride') { res = (arg1 * arg2) / m / m; } else if (type === 'except') { res = (arg1 / arg2); } return res; }; /** * 对字符串保留小数 * @param value 原始值,有可能大于1 * @param num 位数 */ export const toFixed = (str: any, num: number = 2) => { try { if (typeof (str) === "string") { str = parseFloat(str); } else if (typeof (str) === "number") { str = str; } else { str = parseFloat(str); } str = FloatPoint(str, 100, 'ride'); str = str.toString(); // 字符串值 const pointIdx = str.indexOf("."); // 字符串中小数点的位置 if (pointIdx !== -1) { if (num > 0) { // 存在小数点的情况下 // 最多保留num位小数 str = str.substring(0, pointIdx + (num + 1)); // 小数位小于num位的情况下,在末尾补零 const decimalStr = str.substring(pointIdx + 1); // 小数位字符串 if (decimalStr.length < num) { for (let i = 0; i < num - decimalStr.length; i++) { str += "0"; } } } else { str = str.substring(0, pointIdx); return parseFloat(str); } } } catch (error) { return 0; } return parseFloat(str); } export function encode(str) { // 对字符串进行编码 const encode = encodeURI(str); // 对编码的字符串转化base64 const base64 = btoa(encode); return base64; } export function decode(base64) { // 对base64转编码 const decode = atob(base64); // 编码转字符串 const str = decodeURI(decode); return str; }