大数转换函数
// 定义一个大数转换函数
function bigNumberTransform(value) {
// 初始化一个数组,用于存储转换后的值
const newValue = ['', '', '']
// 设置一个开始的阈值
let fr = 1000
// 初始的数字长度
let num = 3
// 用于临时存储单位的变量
let text1 = ''
// 用于存储数字转换的因子
let fm = 1
// 循环判断value的大小,决定其大概的位数
while (value / fr >= 1) {
fr *= 10
num += 1
// 打印当前的数字和数字的长度
// console.log('数字', value / fr, 'num:', num)
}
// 如果数字的长度小于等于4,表示在千以内
if (num <= 4) {
newValue[0] = parseInt(value / 1000) + ''
newValue[1] = '千'
}
// 如果数字的长度小于等于8,表示在万以内
else if (num <= 8) {
text1 = parseInt(num - 4) / 3 > 1 ? '千万' : '万'
fm = text1 === '万' ? 10000 : 10000000
if (value % fm === 0) {
newValue[0] = parseInt(value / fm) + ''
} else {
newValue[0] = parseFloat(value / fm).toFixed(1) + ''
}
newValue[1] = text1
}
// 如果数字的长度小于等于16,表示在亿以内
else if (num <= 16) {
text1 = (num - 8) / 3 > 1 ? '千亿' : '亿'
text1 = (num - 8) / 4 > 1 ? '万亿' : text1
text1 = (num - 8) / 7 > 1 ? '千万亿' : text1
fm = 1
if (text1 === '亿') {
fm = 100000000
} else if (text1 === '千亿') {
fm = 100000000000
} else if (text1 === '万亿') {
fm = 1000000000000
} else if (text1 === '千万亿') {
fm = 1000000000000000
}
if (value % fm === 0) {
newValue[0] = parseInt(value / fm) + ''
} else {
newValue[0] = parseFloat(value / fm).toFixed(2) + ''
}
newValue[1] = text1
}
// 如果数字小于1000,直接返回数字
if (value < 1000) {
newValue[0] = value + ''
newValue[1] = ''
}
// 返回最终的转换结果
return newValue.join('')
}
测试大数转换函数
console.log(bigNumberTransform(11234111)) // 输出: 1123