vue-百分比指令(含小数限制)

·  阅读 861

百分比及保留小数指令

let eventInputChange = (ev, el, vnode) => {
    let { row, prop } = el.value;
    let { value } = ev.querySelector("input");
    let reg = /[^\.\d\-]/gi; // 注释: /[^\.^\d^\-]/gi;
    // let arr = value.split(".");
    // if(arr[0]<100){value = `${arr[0]}${arr[1]? ""+arr[1]:""}`}
    if (/^\-/i.test(value) && value.length > 1) {
        value = "-" + value.substr(1, value.length).replace(/\-/, "");
    }
    if (value > 100) {
        value = "100";
    }
    value = value == "" ? "" : value.replace(reg, "");
    row[prop] = value;
    //vnode.data.model.callback(value);
    // console.log(value);
    //el.value[el.arg] = value;
};
let eventInputBlur = (ev, el, vnode) => {
    let { row, prop } = el.value;
    let num = ev.getElementsByTagName("input")[0].value;
    num = String(num).trim();
    let arg = parseInt(el["arg"]) || null;
    let number = num === "" ? "" : parseFloat(num)||0;
    if (arg != null && number != "") {
        // number= number.toFixed(arg);
        number = currToFixed(number, arg);
    }
    // debugger
    //vnode.data.model.callback(number);
    row[prop] = number;
    vnode.context.$forceUpdate();

    // let num = el.value[el.arg].trim();
    //el.value[el.arg] = num===""? "":parseFloat(el.value[el.arg]);
};
export let number100minus = {
    bind(el, binding, vnode) {
        let input = el.querySelector("input");
        el.addEventListener("input", eventInputChange.bind(this, el, binding, vnode), false);
        input.addEventListener("blur", eventInputBlur.bind(this, el, binding, vnode), false);
    }
};

// 四舍五入
// export function currToFixed(num, s) {
//     return (Math.round(num * Math.pow(10, s)) / Math.pow(10, s) + Math.pow(10, -(s + 1))).toString().slice(0, -1);
// }

// 四舍五入
function currToFixed(value, decimal) {
    const n = Math.pow(10, decimal);
    return divideFloat(Math.round(multiplyFloat(value, n)), n).toFixed(decimal);
}

/**
 * 带有小数的乘法运算
 * @param {Number} arg1 - 因数
 * @param {Number} arg2 - 因数
 */
function multiplyFloat(arg1, arg2) {
    let m = 0;
    const arg1Str = arg1 + "";
    const arg2Str = arg2 + "";
    const arg1StrFloat = arg1Str.split(".")[1];
    const arg2StrFloat = arg2Str.split(".")[1];
    arg1StrFloat && (m += arg1StrFloat.length);
    arg2StrFloat && (m += arg2StrFloat.length);
    const transferResult = +arg1Str.replace(".", "") * +arg2Str.replace(".", "");
    return transferResult / Math.pow(10, m);
}

/**
 * 有小数的除法运算
 * @param {Number} arg1 - 除数
 * @param {Number} arg2 - 被除数
 */
function divideFloat(arg1, arg2) {
    const arg1Str = arg1 + "";
    const arg2Str = arg2 + "";
    const arg1StrFloat = arg1Str.split(".")[1] || "";
    const arg2StrFloat = arg2Str.split(".")[1] || "";
    const m = arg2StrFloat.length - arg1StrFloat.length;
    const transferResult = +arg1Str.replace(".", "") / +arg2Str.replace(".", "");
    return transferResult * Math.pow(10, m);
}

复制代码
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改