前端开发项目中可能会遇到处理返回接口数据,尤其是针对数字进行处理分割。
实现效果如:
12345 => 12,345
封装方法如下:
js方法: function numberFormat(value) { if (value == null || value == "") return "0"; //进行输入内容判断 if (value) { value += ""; if (!value.includes(".")) value += "."; return value.replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => { return $1 + ","; }).replace(/\.$/, ""); } } //console.log(numberFormat(12345.123)) => 12,345.123 vue中即可写在method方法中,用着调用 methods:{ numberFormat(value) { if (value == null || value == "") return "0"; //进行输入内容判断 if (value) { value += ""; if (!value.includes(".")) value += "."; return value.replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => { return $1 + ","; }).replace(/\.$/, ""); } } }
千分位保留两位小数:
function numberFormat2(value) { if (value == null || value == "") return "0";//进行输入内容判断 if (value) { return Number(value).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, ($0, $1) => { return $1 + ","; }).replace(/\.$/, ""); } } //console.log(numberFormat2(12345.123)) => 12,345.12