js将数字转换成万、亿、万亿
1、封装方法
src\utils\utils.ts
// js将数字转换成万、亿、万亿
export const numberFormat = (value)=> {
var param = {};
var k = 10000,
sizes = ['', '万', '亿', '万亿'],
i;
if(value < k){
param.value =value
param.unit=''
}else{
i = Math.floor(Math.log(value) / Math.log(k));
param.value = ((value / Math.pow(k, i))).toFixed(2);
param.unit = sizes[i];
}
return param;
}
// js将数字转换成万 并且保留两位小数
export const keepTwoDecimalFull = (num) => {
if (num > 10000) {
let result = num / 10000;
result = Math.floor(result * 100) / 100;
var s_x = result.toString(); //将数字转换为字符串
var pos_decimal = s_x.indexOf('.'); //小数点的索引值
// 当整数时,pos_decimal=-1 自动补0
if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += '.';
}
// 当数字的长度< 小数点索引+2时,补0
while (s_x.length <= pos_decimal + 2) {
s_x += '0';
}
s_x += '万';
} else {
s_x = num;
}
return s_x
}
2、页面使用
index.vue
<template>
<div>
播放量:<span class="text">{{ numberFormat(playCount) }}</span>
</div>
</template>
<script lang="ts" setup>
import { GetTopList } from '@/server/index'
import { numberFormat } from '@/utils/utils'
let playCount = ref(0)
onMounted(() => {
// 全球榜
GetTopList().then((res) => {
console.log('全球榜单', res)
playCount.value = res.song.playCount
})
})
</script>