vue四舍五入 保留四位小數和只能輸入4位小數


一 這個行內,帶校驗也好用 https://blog.csdn.net/sinat_24230393/article/details/88207929

二 這個也好用

 

 <el-table-column label="數量" min-width="120">
              <template slot-scope="scope">
                <el-form-item
                  :prop="'product_bom.' + scope.$index + '.count'"
                  :ref="'product_bom.' + scope.$index + '.count'"
                  :rules="[
                    { required: true,  message: '請填寫數量,最多5位小數'},
                  ]"
                >
                  <el-input
                    :disabled="inputDisable"
                    v-model="scope.row.count"
                    onkeyup="if(isNaN(value)){value=null}if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+6)}"></el-input>
                </el-form-item>
              </template>
            </el-table-column>

 

 三 基本用法 四舍五入

methods: {
    // 小數點后4位
    decimal4(value) {
      const newVal = parseFloat(value).toFixed(4);
      return newVal;
    },
  },

 四 只能輸入n位小數

 // 保留小數函數
    oninputNum(val, num) {
      if (val) {
        // 轉字符串
        let str = typeof val == "string" ? val : val.toString();
        let len1 = str.substr(0, 1);
        let len2 = str.substr(1, 1);
        // 如果第一位是0,第二位不是點,就用數字把點替換掉
        if (str.length > 1 && len1 == 0 && len2 != ".") {
          str = str.substr(1, 1);
        }
        // 第一位不能是.
        if (len1 == ".") {
          str = "";
        }
        // 限制只能輸入一個小數點
        if (str.indexOf(".") != -1) {
          var str_ = str.substr(str.indexOf(".") + 1);
          if (str_.indexOf(".") != -1) {
            str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
          }
        }
        // 正則替換
        str = str.replace(/[^\d^\.]+/g, ""); // 保留數字和小數點
        if (num == 2) {
          str = str.replace(/^(\-)*(\d+)\.(\d{2}).*$/, "$1$2.$3"); // 小數點后只能輸2位
        }
        if (num == 4) {
          str = str.replace(/^(\-)*(\d+)\.(\d{4}).*$/, "$1$2.$3"); // 小數點后只能輸4位
        }
        return str;
      } else {
        return val;
      }
    },


// 調用 使用
this.value = this.oninputNum(
this.value,
2
);
 

 五 vue校驗只能輸入小數

data() {
    const decimal4 = (rule, value, callback) => {
      const num = /^\d+(\.\d{1,4})?$/;
      if (!num.test(value)) {
        callback(new Error("請輸入數字,最多四位小數!"));
      } else {
        callback();
      }
    };

    return {
      // 加載
      loading: true,
      // 校驗
      Rules: {
        price: [
              {
                required: true,
                message: "請填寫工業價格,最多4位小數",
                validator: decimal2,
                trigger: "blur"
              }
            ],
        }
    }
},

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM