Last active
December 31, 2021 02:45
-
-
Save zmmbreeze/6017772 to your computer and use it in GitHub Desktop.
为数字加上单位:万或亿
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 为数字加上单位:万或亿 | |
* | |
* 例如: | |
* 1000.01 => 1000.01 | |
* 10000 => 1万 | |
* 99000 => 9.9万 | |
* 566000 => 56.6万 | |
* 5660000 => 566万 | |
* 44440000 => 4444万 | |
* 11111000 => 1111.1万 | |
* 444400000 => 4.44亿 | |
* 40000000,00000000,00000000 => 4000万亿亿 | |
* 4,00000000,00000000,00000000 => 4亿亿亿 | |
* | |
* @param {number} number 输入数字. | |
* @param {number} decimalDigit 小数点后最多位数,默认为2 | |
* @return {string} 加上单位后的数字 | |
*/ | |
function addChineseUnit() { | |
var addWan = function(integer, number, mutiple, decimalDigit) { | |
var digit = getDigit(integer); | |
if (digit > 3) { | |
var remainder = digit % 8; | |
if (remainder >= 5) { // ‘十万’、‘百万’、‘千万’显示为‘万’ | |
remainder = 4; | |
} | |
return Math.round(number / Math.pow(10, remainder + mutiple - decimalDigit)) / Math.pow(10, decimalDigit) + '万'; | |
} else { | |
return Math.round(number / Math.pow(10, mutiple - decimalDigit)) / Math.pow(10, decimalDigit); | |
} | |
}; | |
var getDigit = function(integer) { | |
var digit = -1; | |
while (integer >= 1) { | |
digit++; | |
integer = integer / 10; | |
} | |
return digit; | |
}; | |
return function(number, decimalDigit) { | |
decimalDigit = decimalDigit == null ? 2 : decimalDigit; | |
var integer = Math.floor(number); | |
var digit = getDigit(integer); | |
// ['个', '十', '百', '千', '万', '十万', '百万', '千万']; | |
var unit = []; | |
if (digit > 3) { | |
var multiple = Math.floor(digit / 8); | |
if (multiple >= 1) { | |
var tmp = Math.round(integer / Math.pow(10, 8 * multiple)); | |
unit.push(addWan(tmp, number, 8 * multiple, decimalDigit)); | |
for (var i = 0; i < multiple; i++) { | |
unit.push('亿'); | |
} | |
return unit.join(''); | |
} else { | |
return addWan(integer, number, 0, decimalDigit); | |
} | |
} else { | |
return number; | |
} | |
}; | |
}() |
@asins Thx~ 已更新为digit = -1
。
之所以不用string,是不想做次转换和创建数组。
给个英文的格式
// n 数字
// d 小数位数
function m(n, d) {
var x = ('' + parseInt(n, 10)).length,
d = Math.pow(10, d),
arr = " kMGTPE";
x -= x % 3;
return Math.round(n * d / Math.pow(10, x)) / d + arr[x / 3].trim();
}
这样更好
function transform(num) {
const reg = /(\d)(\d)(\d{3})$/
return `${num}`.replace(reg, `$1万$2千$3`)
}
transform(121235810)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
getDigit 方法一开始应该就设置digit = -1;这样在while之后不用再来一次digit--了
另,看明白这方法的作用后觉得有更好的方式
getDigit = function(num){
var num = String(num).split('.')[0];
return num.length - 1;
}