1. 程式人生 > 其它 >el-input輸入金額,保留兩位小數

el-input輸入金額,保留兩位小數

技術標籤:踩坑記錄javascriptcssvue.js

需求:“只允許輸入金額保留兩位小數”,有2種實現方法

方法一(通過正則控制):

html:

<el-input
  v-model="inputTable.amount"
  @input="formatNum(form.amount, 'amount')"
></el-input>

js:

formatNum(val, key) {
  let temp = val.toString();
  temp = temp.replace(/。/g, ".");
  temp = temp.replace(/[^\d.]/g, ""); //清除"數字"和"."以外的字元
  temp = temp.replace(/^\./g, ""); //驗證第一個字元是數字
  temp = temp.replace(/\.{2,}/g, ""); //只保留第一個, 清除多餘的
  temp = temp.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  temp = temp.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); //只能輸入兩個小數
  this.form[key] = temp;
},
方法二(使用元件):

這個是我最近才發現的,方便多了TT
設定精度precision,即可四捨五入;
再改改樣式,隱藏按鈕,靠左對齊,最後效果和普通的input無異

 <el-input-number v-model="num" :precision="2"></el-input-number>

在這裡插入圖片描述