Skip to content

金额格式化

js
moneyFormatter(key) {
    const formatMoney = (money, decimals = 2) => {
		return new Intl.NumberFormat("zh-CN", {
			style: "currency",
			currency: "CNY",
			currencyDisplay: "symbol",
			maximumFractionDigits: decimals,
		}).format(money);
    };
    var reg2 = new RegExp("¥")
	return formatMoney(key, 2).replace(reg2, "") // 去掉 ¥
},
moneyFormatter(key) {
    const formatMoney = (money, decimals = 2) => {
		return new Intl.NumberFormat("zh-CN", {
			style: "currency",
			currency: "CNY",
			currencyDisplay: "symbol",
			maximumFractionDigits: decimals,
		}).format(money);
    };
    var reg2 = new RegExp("¥")
	return formatMoney(key, 2).replace(reg2, "") // 去掉 ¥
},

金额格式化+Vue2+ElementUI+Table组件

js
formatter(row, column, cellValue, index) {
	if (!cellValue) {
		return '¥0.00'
	}
	const formatMoney = (money, decimals = 2) => {
		return new Intl.NumberFormat("zh-CN", {
			style: "currency", // 货币形式
			currency: "CNY", // "CNY"是人民币
			currencyDisplay: "symbol", // 默认“symbol”,中文中代表“¥”符号
			// useGrouping: true, // 是否使用分组分隔符,如千位分隔符或千/万/亿分隔符,默认为true
			// minimumIntegerDigits: 1, // 使用的整数数字的最小数目.可能的值是从1到21,默认值是1
			// minimumFractionDigits: 2, // 使用的小数位数的最小数目.可能的值是从 0 到 20
			maximumFractionDigits: decimals, // 使用的小数位数的最大数目。可能的值是从 0 到 20
		}).format(money);
	};
	return formatMoney(cellValue, 2)
},
formatter(row, column, cellValue, index) {
	if (!cellValue) {
		return '¥0.00'
	}
	const formatMoney = (money, decimals = 2) => {
		return new Intl.NumberFormat("zh-CN", {
			style: "currency", // 货币形式
			currency: "CNY", // "CNY"是人民币
			currencyDisplay: "symbol", // 默认“symbol”,中文中代表“¥”符号
			// useGrouping: true, // 是否使用分组分隔符,如千位分隔符或千/万/亿分隔符,默认为true
			// minimumIntegerDigits: 1, // 使用的整数数字的最小数目.可能的值是从1到21,默认值是1
			// minimumFractionDigits: 2, // 使用的小数位数的最小数目.可能的值是从 0 到 20
			maximumFractionDigits: decimals, // 使用的小数位数的最大数目。可能的值是从 0 到 20
		}).format(money);
	};
	return formatMoney(cellValue, 2)
},

DANGER

toFixed具有精度问题,不建议使用!

js
Formater(cellValue) {
    if (cellValue == 0) {
        return '¥0.00'
    } else if (!cellValue) {
        return '-'
    }
    function number_format(number, decimals, dec_point, thousands_sep) {
        number = (number + '').replace(/[^0-9+-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number,
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
            dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
            s = '',
            toFixedFix = function (n, prec) {
                var k = Math.pow(10, prec);
                return '' + Math.ceil(n * k) / k;
            };

        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        var re = /(-?\d+)(\d{3})/;
        while (re.test(s[0])) {
            s[0] = s[0].replace(re, "$1" + sep + "$2");
        }

        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
    }
    var num = number_format(cellValue, 2, ".", ",")
    return "¥" + num
}
Formater(cellValue) {
    if (cellValue == 0) {
        return '¥0.00'
    } else if (!cellValue) {
        return '-'
    }
    function number_format(number, decimals, dec_point, thousands_sep) {
        number = (number + '').replace(/[^0-9+-Ee.]/g, '');
        var n = !isFinite(+number) ? 0 : +number,
            prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
            sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
            dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
            s = '',
            toFixedFix = function (n, prec) {
                var k = Math.pow(10, prec);
                return '' + Math.ceil(n * k) / k;
            };

        s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
        var re = /(-?\d+)(\d{3})/;
        while (re.test(s[0])) {
            s[0] = s[0].replace(re, "$1" + sep + "$2");
        }

        if ((s[1] || '').length < prec) {
            s[1] = s[1] || '';
            s[1] += new Array(prec - s[1].length + 1).join('0');
        }
        return s.join(dec);
    }
    var num = number_format(cellValue, 2, ".", ",")
    return "¥" + num
}

小写转大写

js
const digitToCNchar = money => {
const digit = ["", "", "", "", "", "", "", "", "", ""];
const declmalUtil = ["", ""];
const IntUtilExc = ["", "", "亿", ""];
const IntUtilBac = ["", "", "", ""];
const head = money < 0 ? "" : "";
money = Math.abs(money);
let res = "";
//处理小数
for (let i = 0; i < declmalUtil.length; i++) {
    let a = Math.pow(10, i + 1);
    a = Math.floor(a * money) % 10;
    res += (digit[a] + declmalUtil[i]).replace(/(.)+/, '');
}
if (res.length < 1) {
    res = "";
}
//处理整数部分
let IntPart = Math.floor(money);
for (let i = 0; i < IntUtilExc.length && IntPart > 0; i++) {
        let part = "";
        for (let j = 0; j < IntUtilBac.length; j++) {
            let a = IntPart % 10;
            IntPart = Math.floor(IntPart / 10);
            part = digit[a] + IntUtilBac[j] + part;
        }
        res = part + IntUtilExc[i] + res;
    }
    res = res.replace(/([拾佰仟])*零元/, "");
    res = res.replace(/^(.)+/, "");
    res = res.replace(/([拾佰仟])+/g, "");
    res = res.replace(/([万亿兆])+/g, "$1");
    res = res.replace(/([万亿兆])+/g, "");
    res = res.replace(/^$/, "零元整");
    return head + res;
}

// 测试
const money = digitToCNchar('3057900.89')
console.log(money) //叁佰零伍万柒仟玖佰元捌角玖分
const digitToCNchar = money => {
const digit = ["", "", "", "", "", "", "", "", "", ""];
const declmalUtil = ["", ""];
const IntUtilExc = ["", "", "亿", ""];
const IntUtilBac = ["", "", "", ""];
const head = money < 0 ? "" : "";
money = Math.abs(money);
let res = "";
//处理小数
for (let i = 0; i < declmalUtil.length; i++) {
    let a = Math.pow(10, i + 1);
    a = Math.floor(a * money) % 10;
    res += (digit[a] + declmalUtil[i]).replace(/(.)+/, '');
}
if (res.length < 1) {
    res = "";
}
//处理整数部分
let IntPart = Math.floor(money);
for (let i = 0; i < IntUtilExc.length && IntPart > 0; i++) {
        let part = "";
        for (let j = 0; j < IntUtilBac.length; j++) {
            let a = IntPart % 10;
            IntPart = Math.floor(IntPart / 10);
            part = digit[a] + IntUtilBac[j] + part;
        }
        res = part + IntUtilExc[i] + res;
    }
    res = res.replace(/([拾佰仟])*零元/, "");
    res = res.replace(/^(.)+/, "");
    res = res.replace(/([拾佰仟])+/g, "");
    res = res.replace(/([万亿兆])+/g, "$1");
    res = res.replace(/([万亿兆])+/g, "");
    res = res.replace(/^$/, "零元整");
    return head + res;
}

// 测试
const money = digitToCNchar('3057900.89')
console.log(money) //叁佰零伍万柒仟玖佰元捌角玖分

指数运算

一般我们使用 Math.pow() 进行指数运算,现在我们可以使用双星号 (**)

js
// 常规写法
const power = Math.pow(4, 3) // 64

// 简写
const power = 4 ** 3 // 64
// 常规写法
const power = Math.pow(4, 3) // 64

// 简写
const power = 4 ** 3 // 64

判断数字为奇数或者偶数

取模运算符 % 可以很好地完成这个任务

js
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: true
console.log(isEven(3));
// Result: false
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: true
console.log(isEven(3));
// Result: false

保留指定的小数位

js
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1) // 25.1
toFixed(25.198726354, 2) // 25.19
toFixed(25.198726354, 3) // 25.198
toFixed(25.198726354, 4) // 25.1987
toFixed(25.198726354, 5) // 25.19872
toFixed(25.198726354, 6) // 25.198726
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1) // 25.1
toFixed(25.198726354, 2) // 25.19
toFixed(25.198726354, 3) // 25.198
toFixed(25.198726354, 4) // 25.1987
toFixed(25.198726354, 5) // 25.19872
toFixed(25.198726354, 6) // 25.198726

:::success 探究JS内置toFixed(n)方法 区别:四舍五入 :::

获取所有参数的平均值

可以使用 reduce() 函数来计算所有参数的平均值

js
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4)
// Result: 2.5
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4)
// Result: 2.5

转换华氏/摄氏

再也不怕处理温度单位了,下面两个函数是两个温度单位的相互转换。

js
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
// Examples
celsiusToFahrenheit(15);    // 59
celsiusToFahrenheit(0);     // 32
celsiusToFahrenheit(-20);   // -4
fahrenheitToCelsius(59);    // 15
fahrenheitToCelsius(32);    // 0
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
// Examples
celsiusToFahrenheit(15);    // 59
celsiusToFahrenheit(0);     // 32
celsiusToFahrenheit(-20);   // -4
fahrenheitToCelsius(59);    // 15
fahrenheitToCelsius(32);    // 0

求n个数的平均值

js
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5