用javascript格式化数字,而不进行更改

Formating numbers in javascript, without altering

本文关键字:javascript 格式化 数字      更新时间:2023-09-26

我正在寻找一个jQuery插件或regex解决方案,以在JavaScript中格式化数字,而无需更改、舍入或添加零。一个数字进入,然后按照三条规则返回:-千位分隔符-小数位数-所需分离器

以下是我正在寻找的一些例子:

Thousands: Comma, Decimals: 0, Separator: Point
Input: 1000 » Output: 1,000
Input: 100000 » Output: 100,000
Thousands: Space, Decimals: 2, Separator: Comma
Input: 1000 » Output: 10,00
Input: 100000 » Output: 1 000,00
Thousands: Comma, Decimals: 1, Separator: Point
Input: 1000 » Output: 100.0
Input: 100000 » Output: 10,000.0

试试这个函数:

function format(prop) {
    prop.input = String(prop.input);
    var input = prop.input, decimals = '';
    if (prop.decimals) {
        input = prop.input.slice(0, -prop.decimals);
        decimals = prop.separator + prop.input.slice(-prop.decimals);
    }
    return input.replace(/(?!^)(?=(...)+$)/g, prop.thousands) + decimals;
}

示例:

format({
    input: 100000,
    thousands: ' ',
    decimals: 2,
    separator: ','
});
// "1 000,00"

我为您制作了一个快速函数。

function lindqvistFormat(input, thouSep, decimals, decSep) {
    var inStr = (input * (input < 0 ? -1 : 1)).toFixed(0);
    while(inStr.length < decimals + 1) inStr = "0" + inStr;
    var leftPart = inStr.substr(0, inStr.length - decimals), rightPart = decimals ? decSep + inStr.substr(-decimals) : "";
    return (input < 0 ? "-" : "") + leftPart.replace(/(?!^)(?=(...)+$)/g, thouSep) + rightPart;
}

示例:lindqvistFormat(-1234567890, " ", 2, ".")将导致-12 345 678.90

它还处理位数少于请求小数位数的值,依此类推

我知道它的工作原理并不是很清楚,它使用了一些快捷方式,但它是有效的,我现在没有太多时间来解释它是如何工作的。我决定无论如何都发布它,因为事实上,它确实为您的问题提供了解决方案。

EDIT:user6188402的regex实际上比我的解决方案聪明得多,而且不需要我的extLeftPart,所以我更改了我的解决方法,使其工作方式与他的类似。因此,regex部分的功劳归于user6188402。(我以前的解决方案是使用一个extLeftPart,它用伪字符填充,使长度可以除以3,然后使用Array.prototype.join(extLeftPart.match(/.{3}/g), thouSep),然后在最后再次删除填充。)