标签:ever asc pre string nts == code numbers let
1
function formatNumber1 (number) {
const base = 3
number = Number(number) // 只要包含字符 都会转为NaN
let numberStr = number.toString() // NaN => ‘NaN‘
if (numberStr === ‘NaN‘) {
return ‘0‘
}
const isFloat = numberStr.indexOf(‘.‘)>-1
const floatStr = isFloat ? numberStr.split(‘.‘)[1] : ‘‘
const intStr = numberStr.split(‘.‘)[0]
const len = intStr.length
if (len <= base) {
return numberStr
}
let str = ‘‘
const m = len % base
let t = Math.floor(len / base)
if (m === 0) {
t--
}
for (let i = 0; i<t; i++) {
str = "," + intStr.substring(len - (i + 1) * base, len - i * base) + str
}
str = intStr.substring(0, m ? m : base) + str
return isFloat ? str + ‘.‘ + floatStr : str
}
2
function formatNumber2 (number) {
const base = 3
number = Number(number) // 只要包含字符 都会转为NaN
let numberStr = number.toString() // NaN => ‘NaN‘
if (numberStr === ‘NaN‘) {
return ‘0‘
}
const isFloat = numberStr.indexOf(‘.‘)>-1
const floatStr = isFloat ? numberStr.split(‘.‘)[1] : ‘‘
const intStr = numberStr.split(‘.‘)[0]
const len = intStr.length
if (len <= base) {
return numberStr
}
let str = ‘‘
const m = len % base
let t = Math.floor(len / base)
let i = 0
if (m === 0) {
t--
for (i; i < t; i++) {
str += intStr.substring(m + i * base, m + (i + 1) * base) + ‘,‘
}
} else {
str = intStr.substring(0, m) + ‘,‘
i = 1
for (i; i < t; i++) {
str += intStr.substring(m + (i - 1) * base, m + i * base) + ‘,‘
}
}
str += intStr.substring(len - base)
return isFloat ? str + ‘.‘ + floatStr : str
}
3
function formatNumber3 (number) {
number = Number(number)
let numStr = number.toString()
if (numStr === ‘NaN‘) {
return ‘0‘
}
const floatStr = numStr.split(‘.‘)[1] ? numStr.split(‘.‘)[1] : ‘‘
numStr = numStr.split(‘.‘)[0].split(‘‘).reverse().join(‘‘)
const pattern = /([\S]{3})/g
numStr = numStr.replace(/\s/, ‘‘).replace(pattern, function (match) {
return match + ‘,‘
})
numStr = numStr.split(‘‘).reverse().join(‘‘)
if (numStr[0] === ‘,‘) {
numStr = numStr.substring(1)
}
// console.log(numStr);
return floatStr ? numStr + ‘.‘ + floatStr : numStr
}
标签:ever asc pre string nts == code numbers let
原文地址:https://www.cnblogs.com/zhanglw456/p/13073145.html