js中保留4位小数,超过4位截取保留4位,不足4位保留原位数不补0

    //保留4位小数
    var number = 12.3321432;
    number = String(number).replace(/^(.*\..{4}).*$/,"$1");
    number = Number(number); // number = 12.3321

    //保留2位小数
    var reg = /^(.*\..{2}).*$/;
    var number2 = 12.3;
    number2 = String(number2).replace(reg ,"$1");
    number2 = Number(number2); // number2 = 12.3  不足保留位数不补0

你可能感兴趣的:(js)