需求 只能輸入數字
輸入字母和特殊字符自動過濾掉
輸入完成失焦自動加.00 若是輸入了小數自動四捨五入爲22.22相似這樣格式html
let number = { twoWay: true, bind:function (el) { el.addEventListener('blur',function () { // let value = formatNumber(el.value,2,0) let value (function(){ value = formatNumber(el.value,2,0) return value })() el.value =value }) }, update:function (el,binding,vnode) { if(el.value !== ''){ el.value = el.value.replace(/[^0-9.]+/g, ''); } } } /** * 將數值四捨五入後格式化. * @param num 數值(Number或者String) * @param cent 要保留的小數位(Number) * @param isThousand 是否須要千分位 0:不須要,1:須要(數值類型); * @return 格式的字符串,如'1,234,567.45' * @type String */ function formatNumber(num,cent,isThousand) { num = num.toString().replace(/\$|\,/g,''); // 檢查傳入數值爲數值類型 if(isNaN(num)) num = "0"; // 獲取符號(正/負數) let sign = (num == (num = Math.abs(num))); num = Math.floor(num*Math.pow(10,cent)+0.50000000001); // 把指定的小數位先轉換成整數.多餘的小數位四捨五入 let cents = num%Math.pow(10,cent); // 求出小數位數值 num = Math.floor(num/Math.pow(10,cent)).toString(); // 求出整數位數值 cents = cents.toString(); // 把小數位轉換成字符串,以便求小數位長度 // 補足小數位到指定的位數 while(cents.length<cent) cents = "0" + cents; if(isThousand) { // 對整數部分進行千分位格式化. for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3)); } if (cent > 0) return (((sign)?'':'-') + num + '.' + cents); else return (((sign)?'':'-') + num); } export { number }
用法vue
import {number} from './numberDirective' import Vue from 'vue' Vue.directive('numbers',number)