效果展示:
业务需求:将数字类型的金额,转为类似1,234,554.00格式的金额
页面:
<view class="tr u-flex" v-for="(item,index) in dataList" :key="index" @click="goEverydaySummary(item)">
<view class="td u-flex-3 name u-text-left" ">{{item.receiveAddress}}</view>
<view class="td u-flex-2 amt">{{item.amt | formatMoney}}</view>
<view class="td u-flex-2 amt">{{item.taxPrice | formatMoney}}</view>
<view class="td u-flex-2 amt u-text-right">{{item.taxAmt | formatMoney}}</view>
<u-icon class="arrow" name="arrow-right" size="30" color="#8799a3"></u-icon>
</view>
逻辑层
import { formatMoney } from '@/lib/util.js';
export default{
filters: {formatMoney}
}
单独的utils.js文件
//金额转千位符
export const formatMoney = (val) => {
if (!val || val==0) return '0.00';
if (val == Infinity) return '∞';
val = val.toString().replace('[$,]', '');
if (isNaN(val)) {
val = "0";
}
let sign = (val == (val = Math.abs(val)));
val = Math.floor(val * 100 + 0.50000000001);
let cents = val % 100;
val = Math.floor(val / 100).toString();
if (cents < 10) {
cents = "0" + cents
}
for (var i = 0; i < Math.floor((val.length - (1 + i)) / 3); i++) {
val = val.substring(0, val.length - (4 * i + 3)) + ',' + val.substring(val.length - (4 * i + 3));
}
return (((sign) ? '' : '-') + val + '.' + cents);
};