创作者微信小程序端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.7 KiB

<template>
<view v-if="hidden"
class="money-format-view money-hidden"
:style="{fontSize: size + 'rpx', color: color}"
>
<span class="character-span" v-if="character">{{ character }}</span> {{ hiddenValue }}
</view>
<view v-else
class="money-format-view money-show"
:style="{fontSize: size + 'rpx', color: color}"
>
<span class="character-span" v-if="character">{{ character }}</span> {{ moneyValue }}
</view>
</template>
<script>
export default {
name: "MoneyView",
props: {
character: {
type: String,
default: undefined
},
color:{
type: String,
default: '#FFF'
},
size: {
type: Number,
default: 24
},
value: {
type: Number,
default: 0.00
},
hidden: {
type: Boolean,
default: false
}
},
data() {
return {
moneyValue: '0.00',
hiddenValue: '******',
}
},
created() {
this.moneyValue = this.moneyFormat(this.value, 2, ',')
},
methods: {
thousandFormat(num, split) {
const len = num.length
return len <= 3 ? num : this.thousandFormat(num.substr(0, len - 3)) + split + num.substr(len - 3, 3)
},
moneyFormat(num, decimal = 2, split = ',') {
/*
parameter
num格式化目标数字
decimal保留几位小数默认2位
split千分位分隔符默认为,
moneyFormat(123456789.87654321, 2, ',') // 123,456,789.88
*/
if (isFinite(num)) { // num是数字
if (num === 0) { // 为0
return "0.00"
} else { // 非0
let res = 0;
const dotIndex = String(num).indexOf('.');
if (dotIndex === -1) { // 整数
res = this.thousandFormat(String(num), split) + '.' + '0'.repeat(decimal)
} else { // 非整数
// js四舍五入 Math.round():正数时4舍5入,负数时5舍6入
// Math.round(1.5) = 2
// Math.round(-1.5) = -1
// Math.round(-1.6) = -2
// 保留decimals位小数
const numStr = String((Math.round(num * Math.pow(10, decimal)) / Math.pow(10, decimal)).toFixed(decimal)) // 四舍五入,然后固定保留2位小数
const decimals = numStr.slice(dotIndex, dotIndex + decimal + 1) // 截取小数位
res = this.thousandFormat(numStr.slice(0, dotIndex), split) + decimals
}
return res
}
} else {
return '0.00'
}
}
},
watch: {
value(newValue) {
this.moneyValue = this.moneyFormat(newValue, 2, ',')
},
}
}
</script>
<style scoped lang="scss">
.money-format-view {
//min-width: 80rpx;
}
.money-hidden {
}
</style>