【问题标题】:Formating numbers in javascript, without altering在javascript中格式化数字,而不改变
【发布时间】:2016-05-03 12:20:09
【问题描述】:

我正在寻找一个 jQuery 插件或正则表达式解决方案来格式化 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

【问题讨论】:

  • 不改变...结果?
  • 我把标题改成了“...没有改变”。我找到的所有解决方案在定义小数时都会添加两个零。我想要一个根本不添加任何数字的解决方案。只有分隔符。
  • 负数如何格式化?
  • 如何将1000格式化为10,00?有些东西我没有得到
  • @Gerard 除了添加分隔符(用于千位和小数的空格、逗号或点)之外,什么都不应该改变。负数应继续为负数。

标签: javascript jquery regex


【解决方案1】:

试试这个功能:

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"

【讨论】:

  • 感谢您的帮助,非常感谢。但是,如果我输入 100,我会得到“1,1”,它应该是 1,00。 1200 变为 12,12。
【解决方案2】:

我为你做了一个快速函数。

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

它还处理位数少于请求的小数位数的值,等等。

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

编辑: user6188402 的正则表达式实际上比我的解决方案聪明得多,并且不需要我拥有的extLeftPart,因此我将解决方案更改为与他的类似。因此,正则表达式部分的功劳归于 user6188402。 (我的旧解决方案是使用 extLeftPart 填充虚拟字符以使长度可被 3 整除,然后使用 Array.prototype.join(extLeftPart.match(/.{3}/g), thouSep) 并在最后再次删除填充。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 2020-08-20
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多