JavaScript 中的数字格式与 C# 类似

发布于 2024-09-27 02:23:15 字数 149 浏览 9 评论 0原文

有没有一种简单的方法可以在 JavaScript 中格式化数字,类似于 C#(或 VB.NET)中通过 ToString("format_provider")String.Format()?

Is there a simple way to format numbers in JavaScript, similar to the formatting methods available in C# (or VB.NET) via ToString("format_provider") or String.Format()?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

深居我梦 2024-10-04 02:23:15

Generally

In jQuery

活泼老夫 2024-10-04 02:23:15

是的,肯定有一种方法可以在 javascript 中正确格式化数字,例如:

var val=2489.8237

val.toFixed(3) //returns 2489.824 (round up)
val.toFixed(2) //returns 2489.82
val.toFixed(7) //returns 2489.8237000 (padding)

使用variablename.toFixed

还有另一个函数 toPrecision()
有关更多详细信息,您还可以访问

http://raovishal.blogspot。 com/2012/01/number-format-in-javascript.html

Yes, there is definitely a way to format numbers properly in javascript, for example:

var val=2489.8237

val.toFixed(3) //returns 2489.824 (round up)
val.toFixed(2) //returns 2489.82
val.toFixed(7) //returns 2489.8237000 (padding)

With the use of variablename.toFixed .

And there is another function toPrecision() .
For more detail you also can visit

http://raovishal.blogspot.com/2012/01/number-format-in-javascript.html

梦回旧景 2024-10-04 02:23:15

这是一个简单的 JS 函数,用于向字符串格式的整数添加逗号。它将处理整数或小数。您可以向其传递数字或字符串。显然它返回一个字符串。

function addCommas(str) {
    var parts = (str + "").split("."),
        main = parts[0],
        len = main.length,
        output = "",
        first = main.charAt(0),
        i;

    if (first === '-') {
        main = main.slice(1);
        len = main.length;    
    } else {
        first = "";
    }
    i = len - 1;
    while(i >= 0) {
        output = main.charAt(i) + output;
        if ((len - i) % 3 === 0 && i > 0) {
            output = "," + output;
        }
        --i;
    }
    // put sign back
    output = first + output;
    // put decimal part back
    if (parts.length > 1) {
        output += "." + parts[1];
    }
    return output;
}

下面是一组测试用例: http://jsfiddle.net/jfriend00/6y57j/

可以看到它在之前的 jsFiddle 中使用:http://jsfiddle.net/jfriend00/sMnjT/。通过简单的 Google 搜索“javascript add commas”,您也可以找到处理十进制数字的函数。

将数字转换为字符串可以通过多种方式完成。最简单的方法就是将其添加到字符串中:

var myNumber = 3;
var myStr = "" + myNumber;   // "3"

在 jsFiddle 的上下文中,您可以通过更改此行将逗号放入计数器中:

jTarget.text(current);

对此:

jTarget.text(addCommas(current));

您可以在此处看到它的工作方式: http://jsfiddle.net/jfriend00/CbjSX/

Here's a simple JS function to add commas to an integer number in string format. It will handle whole numbers or decimal numbers. You can pass it either a number or a string. It obviously returns a string.

function addCommas(str) {
    var parts = (str + "").split("."),
        main = parts[0],
        len = main.length,
        output = "",
        first = main.charAt(0),
        i;

    if (first === '-') {
        main = main.slice(1);
        len = main.length;    
    } else {
        first = "";
    }
    i = len - 1;
    while(i >= 0) {
        output = main.charAt(i) + output;
        if ((len - i) % 3 === 0 && i > 0) {
            output = "," + output;
        }
        --i;
    }
    // put sign back
    output = first + output;
    // put decimal part back
    if (parts.length > 1) {
        output += "." + parts[1];
    }
    return output;
}

Here's a set of test cases: http://jsfiddle.net/jfriend00/6y57j/

You can see it being used in this previous jsFiddle: http://jsfiddle.net/jfriend00/sMnjT/. You can find functions that will handle decimal numbers too with a simple Google search for "javascript add commas".

Converting a number to a string can be done many ways. The easiest is just to add it to a string:

var myNumber = 3;
var myStr = "" + myNumber;   // "3"

Within, the context of your jsFiddle, you'd get commas into the counter by changing this line:

jTarget.text(current);

to this:

jTarget.text(addCommas(current));

You can see it working here: http://jsfiddle.net/jfriend00/CbjSX/

怪我鬧 2024-10-04 02:23:15

我编写了一个简单的函数(不需要另一个 jQuery 插件!!),如果数字不是以数字开头,则将数字转换为十进制分隔的字符串或空字符串:

function format(x) {
    return isNaN(x)?"":x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

format(578999); 结果为 578,999

format(10); 结果为 10

如果您想要小数点而不是逗号,只需替换逗号即可在带有小数点的代码中。

评论之一正确地指出这仅适用于整数,通过一些小的调整,您可以使其也适用于浮点:

function format(x) {
    if(isNaN(x))return "";

    n= x.toString().split('.');
    return n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")+(n.length>1?"."+n[1]:"");
}

I wrote a simple function (not yet another jQuery plugin needed!!) that converts a number to a decimal separated string or an empty string if the number wasn't a number to begin with:

function format(x) {
    return isNaN(x)?"":x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

format(578999); results in 578,999

format(10); results in 10

if you want to have a decimal point instead of a comma simply replace the comma in the code with a decimal point.

One of the comments correctly stated this only works for integers, with a few small adaptions you can make it work for floating points as well:

function format(x) {
    if(isNaN(x))return "";

    n= x.toString().split('.');
    return n[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",")+(n.length>1?"."+n[1]:"");
}
如日中天 2024-10-04 02:23:15

这里有一些解决方案,都通过了测试套件,包括测试套件和基准测试,如果你想复制粘贴来测试,请尝试 这个要点

方法 0 (RegExp)

基于 https://stackoverflow.com/a/14428340/1877620,但修复是否有没有小数点。

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');
        a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '
amp;,');
        return a.join('.');
    }
}

方法 1

if (typeof Number.prototype.format1 === 'undefined') {
    Number.prototype.format1 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.'),
            // skip the '-' sign
            head = Number(this < 0);

        // skip the digits that's before the first thousands separator 
        head += (a[0].length - head) % 3 || 3;

        a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',
amp;');
        return a.join('.');
    };
}

方法 2(拆分为数组)

if (typeof Number.prototype.format2 === 'undefined') {
    Number.prototype.format2 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');

        a[0] = a[0]
            .split('').reverse().join('')
            .replace(/\d{3}(?=\d)/g, '
amp;,')
            .split('').reverse().join('');

        return a.join('.');
    };
}

方法 3(循环)

if (typeof Number.prototype.format3 === 'undefined') {
    Number.prototype.format3 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('');
        a.push('.');

        var i = a.indexOf('.') - 3;
        while (i > 0 && a[i-1] !== '-') {
            a.splice(i, 0, ',');
            i -= 3;
        }

        a.pop();
        return a.join('');
    };
}

示例

console.log('======== Demo ========')
var n = 0;
for (var i=1; i<20; i++) {
    n = (n * 10) + (i % 10)/100;
    console.log(n.format(2), (-n).format(2));
}

分隔符

如果我们想要自定义千位分隔符或小数分隔符,请使用 Replace():

123456.78.format(2).replace(',', ' ').replace('.', ' ');

测试套件

function assertEqual(a, b) {
    if (a !== b) {
        throw a + ' !== ' + b;
    }
}

function test(format_function) {
    console.log(format_function);
    assertEqual('NaN', format_function.call(NaN, 0))
    assertEqual('Infinity', format_function.call(Infinity, 0))
    assertEqual('-Infinity', format_function.call(-Infinity, 0))

    assertEqual('0', format_function.call(0, 0))
    assertEqual('0.00', format_function.call(0, 2))
    assertEqual('1', format_function.call(1, 0))
    assertEqual('-1', format_function.call(-1, 0))
    // decimal padding
    assertEqual('1.00', format_function.call(1, 2))
    assertEqual('-1.00', format_function.call(-1, 2))
    // decimal rounding
    assertEqual('0.12', format_function.call(0.123456, 2))
    assertEqual('0.1235', format_function.call(0.123456, 4))
    assertEqual('-0.12', format_function.call(-0.123456, 2))
    assertEqual('-0.1235', format_function.call(-0.123456, 4))
    // thousands separator
    assertEqual('1,234', format_function.call(1234.123456, 0))
    assertEqual('12,345', format_function.call(12345.123456, 0))
    assertEqual('123,456', format_function.call(123456.123456, 0))
    assertEqual('1,234,567', format_function.call(1234567.123456, 0))
    assertEqual('12,345,678', format_function.call(12345678.123456, 0))
    assertEqual('123,456,789', format_function.call(123456789.123456, 0))
    assertEqual('-1,234', format_function.call(-1234.123456, 0))
    assertEqual('-12,345', format_function.call(-12345.123456, 0))
    assertEqual('-123,456', format_function.call(-123456.123456, 0))
    assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
    assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
    assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
    // thousands separator and decimal
    assertEqual('1,234.12', format_function.call(1234.123456, 2))
    assertEqual('12,345.12', format_function.call(12345.123456, 2))
    assertEqual('123,456.12', format_function.call(123456.123456, 2))
    assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
    assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
    assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
    assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
    assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
    assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
    assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
    assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
    assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}

console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);

基准

function benchmark(f) {
    var start = new Date().getTime();
    f();
    return new Date().getTime() - start;
}

function benchmark_format(f) {
    console.log(f);
    time = benchmark(function () {
        for (var i = 0; i < 100000; i++) {
            f.call(123456789, 0);
            f.call(123456789, 2);
        }
    });
    console.log(time.format(0) + 'ms');
}

async = [];
function next() {
    setTimeout(function () {
        f = async.shift();
        f && f();
        next();
    }, 10);
}

console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
async.push(function () { benchmark_format(Number.prototype.format1); });
async.push(function () { benchmark_format(Number.prototype.format2); });
async.push(function () { benchmark_format(Number.prototype.format3); });
next();

Here are some solutions, all pass the test suite, test suite and benchmark included, if you want copy and paste to test, try This Gist.

Method 0 (RegExp)

Base on https://stackoverflow.com/a/14428340/1877620, but fix if there is no decimal point.

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');
        a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '
amp;,');
        return a.join('.');
    }
}

Method 1

if (typeof Number.prototype.format1 === 'undefined') {
    Number.prototype.format1 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.'),
            // skip the '-' sign
            head = Number(this < 0);

        // skip the digits that's before the first thousands separator 
        head += (a[0].length - head) % 3 || 3;

        a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',
amp;');
        return a.join('.');
    };
}

Method 2 (Split to Array)

if (typeof Number.prototype.format2 === 'undefined') {
    Number.prototype.format2 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');

        a[0] = a[0]
            .split('').reverse().join('')
            .replace(/\d{3}(?=\d)/g, '
amp;,')
            .split('').reverse().join('');

        return a.join('.');
    };
}

Method 3 (Loop)

if (typeof Number.prototype.format3 === 'undefined') {
    Number.prototype.format3 = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('');
        a.push('.');

        var i = a.indexOf('.') - 3;
        while (i > 0 && a[i-1] !== '-') {
            a.splice(i, 0, ',');
            i -= 3;
        }

        a.pop();
        return a.join('');
    };
}

Example

console.log('======== Demo ========')
var n = 0;
for (var i=1; i<20; i++) {
    n = (n * 10) + (i % 10)/100;
    console.log(n.format(2), (-n).format(2));
}

Separator

If we want custom thousands separator or decimal separator, use replace():

123456.78.format(2).replace(',', ' ').replace('.', ' ');

Test suite

function assertEqual(a, b) {
    if (a !== b) {
        throw a + ' !== ' + b;
    }
}

function test(format_function) {
    console.log(format_function);
    assertEqual('NaN', format_function.call(NaN, 0))
    assertEqual('Infinity', format_function.call(Infinity, 0))
    assertEqual('-Infinity', format_function.call(-Infinity, 0))

    assertEqual('0', format_function.call(0, 0))
    assertEqual('0.00', format_function.call(0, 2))
    assertEqual('1', format_function.call(1, 0))
    assertEqual('-1', format_function.call(-1, 0))
    // decimal padding
    assertEqual('1.00', format_function.call(1, 2))
    assertEqual('-1.00', format_function.call(-1, 2))
    // decimal rounding
    assertEqual('0.12', format_function.call(0.123456, 2))
    assertEqual('0.1235', format_function.call(0.123456, 4))
    assertEqual('-0.12', format_function.call(-0.123456, 2))
    assertEqual('-0.1235', format_function.call(-0.123456, 4))
    // thousands separator
    assertEqual('1,234', format_function.call(1234.123456, 0))
    assertEqual('12,345', format_function.call(12345.123456, 0))
    assertEqual('123,456', format_function.call(123456.123456, 0))
    assertEqual('1,234,567', format_function.call(1234567.123456, 0))
    assertEqual('12,345,678', format_function.call(12345678.123456, 0))
    assertEqual('123,456,789', format_function.call(123456789.123456, 0))
    assertEqual('-1,234', format_function.call(-1234.123456, 0))
    assertEqual('-12,345', format_function.call(-12345.123456, 0))
    assertEqual('-123,456', format_function.call(-123456.123456, 0))
    assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
    assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
    assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
    // thousands separator and decimal
    assertEqual('1,234.12', format_function.call(1234.123456, 2))
    assertEqual('12,345.12', format_function.call(12345.123456, 2))
    assertEqual('123,456.12', format_function.call(123456.123456, 2))
    assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
    assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
    assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
    assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
    assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
    assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
    assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
    assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
    assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}

console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);

Benchmark

function benchmark(f) {
    var start = new Date().getTime();
    f();
    return new Date().getTime() - start;
}

function benchmark_format(f) {
    console.log(f);
    time = benchmark(function () {
        for (var i = 0; i < 100000; i++) {
            f.call(123456789, 0);
            f.call(123456789, 2);
        }
    });
    console.log(time.format(0) + 'ms');
}

async = [];
function next() {
    setTimeout(function () {
        f = async.shift();
        f && f();
        next();
    }, 10);
}

console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
async.push(function () { benchmark_format(Number.prototype.format1); });
async.push(function () { benchmark_format(Number.prototype.format2); });
async.push(function () { benchmark_format(Number.prototype.format3); });
next();
东北女汉子 2024-10-04 02:23:15

如果您不想使用 jQuery,请查看 Numeral.js

If you don't want to use jQuery, take a look at Numeral.js

救星 2024-10-04 02:23:15

首先,在 JS 中将整数转换为字符串非常简单:

// Start off with a number
var number = 42;
// Convert into a string by appending an empty (or whatever you like as a string) to it
var string = 42+'';
// No extra conversion is needed, even though you could actually do
var alsoString = number.toString();

如果你有一个数字作为字符串并希望将其转换为整数,则必须对整数使用 parseInt(string) parseFloat(string) 用于浮点数。然后,这两个函数都会返回所需的整数/浮点数。示例:

// Start off with a float as a string
var stringFloat = '3.14';
// And an int as a string
var stringInt = '42';

// typeof stringInt  would give you 'string'

// Get the real float from the string
var realFloat = parseFloat(someFloat);
// Same for the int
var realInt = parseInt(stringInt);

// but typeof realInt  will now give you 'number'

您到底想附加什么等,从您的问题中我仍然不清楚。

Firstly, converting an integer into string in JS is really simple:

// Start off with a number
var number = 42;
// Convert into a string by appending an empty (or whatever you like as a string) to it
var string = 42+'';
// No extra conversion is needed, even though you could actually do
var alsoString = number.toString();

If you have a number as a string and want it to be turned to an integer, you have to use the parseInt(string) for integers and parseFloat(string) for floats. Both of these functions then return the desired integer/float. Example:

// Start off with a float as a string
var stringFloat = '3.14';
// And an int as a string
var stringInt = '42';

// typeof stringInt  would give you 'string'

// Get the real float from the string
var realFloat = parseFloat(someFloat);
// Same for the int
var realInt = parseInt(stringInt);

// but typeof realInt  will now give you 'number'

What exactly are you trying to append etc, remains unclear to me from your question.

揪着可爱 2024-10-04 02:23:15

http://code.google.com/p/javascript-number-formatter/:

  • 简短、快速、灵活且独立。只有 75 行,包括 MIT 许可证信息、空行和信息。评论。
  • 接受标准数字格式,例如 #,##0.00 或带负数 -000.####。
  • 接受任何国家/地区格式,例如 # ##0,00、#,###.##、###.## 或任何类型的非编号符号。
  • 接受任意数量的数字分组。 #,##,#0.000 或 #,###0.## 均有效。
  • 接受任何冗余/防呆格式。 ##,###,##.# 或 0#,#00#.###0# 都可以。
  • 自动数字舍入。
  • 接口简单,只需提供mask &像这样的值: format( "0.0000", 3.141592)

UPDATE

正如 Tomáš Zato 这里所说的一行解决方案:

(666.0).toLocaleString()
numObj.toLocaleString([locales [, options]])

ECMA-262 5.1 版本中描述:

并将在未来版本的浏览器中工作...

http://code.google.com/p/javascript-number-formatter/ :

  • Short, fast, flexible yet standalone. Only 75 lines including MIT license info, blank lines & comments.
  • Accept standard number formatting like #,##0.00 or with negation -000.####.
  • Accept any country format like # ##0,00, #,###.##, #'###.## or any type of non-numbering symbol.
  • Accept any numbers of digit grouping. #,##,#0.000 or #,###0.## are all valid.
  • Accept any redundant/fool-proof formatting. ##,###,##.# or 0#,#00#.###0# are all OK.
  • Auto number rounding.
  • Simple interface, just supply mask & value like this: format( "0.0000", 3.141592)

UPDATE

As say Tomáš Zato here one line solution:

(666.0).toLocaleString()
numObj.toLocaleString([locales [, options]])

which described in ECMA-262 5.1 Edition:

and will work in future versions of browsers...

神也荒唐 2024-10-04 02:23:15

例如:

var flt = '5.99';
var nt = '6';

var rflt = parseFloat(flt);
var rnt = parseInt(nt);

For example:

var flt = '5.99';
var nt = '6';

var rflt = parseFloat(flt);
var rnt = parseInt(nt);
伤痕我心 2024-10-04 02:23:15

使用JQuery

$(document).ready(function()
 {
    //Only number and one dot
    function onlyDecimal(element, decimals)
    {
        $(element).keypress(function(event)
        {
            num = $(this).val() ;
            num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
            {
                event.preventDefault();

            }
            if($(this).val() == parseFloat(num).toFixed(decimals))
            {
                event.preventDefault();
            }
        });
    }

     onlyDecimal("#TextBox1", 3) ;



});

Using JQuery.

$(document).ready(function()
 {
    //Only number and one dot
    function onlyDecimal(element, decimals)
    {
        $(element).keypress(function(event)
        {
            num = $(this).val() ;
            num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
            if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
            {
                event.preventDefault();

            }
            if($(this).val() == parseFloat(num).toFixed(decimals))
            {
                event.preventDefault();
            }
        });
    }

     onlyDecimal("#TextBox1", 3) ;



});

迷离° 2024-10-04 02:23:15

要获得逗号后有 2 个数字的小数,您可以使用:

function nformat(a) {
   var b = parseInt(parseFloat(a)*100)/100;
   return b.toFixed(2);
}

To get a decimal with 2 numbers after the comma, you could just use:

function nformat(a) {
   var b = parseInt(parseFloat(a)*100)/100;
   return b.toFixed(2);
}
清风疏影 2024-10-04 02:23:15

我可以建议 numbro 进行基于区域设置的格式化和 numbro 进行基于区域设置的格式化npmjs.com/package/number-format.js" rel="nofollow noreferrer">number-format.js 适用于一般情况。根据用例将两者结合起来可能会有所帮助。

May I suggest numbro for locale based formatting and number-format.js for the general case. A combination of the two depending on use-case may help.

十雾 2024-10-04 02:23:15

这是另一个版本:

$.fn.digits = function () {
    return this.each(function () {
        var value = $(this).text();
        var decimal = "";
        if (value) {
            var pos = value.indexOf(".");
            if (pos >= 0) {
                decimal = value.substring(pos);
                value = value.substring(0, pos);
            }
            if (value) {
                value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
                if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
                $(this).text(value);
            }
        }
        else {
            value = $(this).val()
            if (value) {
                var pos = value.indexOf(".");
                if (pos >= 0) {
                    decimal = value.substring(pos);
                    value = value.substring(0, pos);
                }
                if (value) {
                    value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
                    if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
                    $(this).val(value);
                }
            }
        }
    })
};

Here's another version:

$.fn.digits = function () {
    return this.each(function () {
        var value = $(this).text();
        var decimal = "";
        if (value) {
            var pos = value.indexOf(".");
            if (pos >= 0) {
                decimal = value.substring(pos);
                value = value.substring(0, pos);
            }
            if (value) {
                value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
                if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
                $(this).text(value);
            }
        }
        else {
            value = $(this).val()
            if (value) {
                var pos = value.indexOf(".");
                if (pos >= 0) {
                    decimal = value.substring(pos);
                    value = value.substring(0, pos);
                }
                if (value) {
                    value = value.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
                    if (!String.isNullOrEmpty(decimal)) value = (value + decimal);
                    $(this).val(value);
                }
            }
        }
    })
};
悲欢浪云 2024-10-04 02:23:15

我做了一个简单的函数,也许有人可以使用它

function secsToTime(secs){
  function format(number){
    if(number===0){
      return '00';
    }else {
      if (number < 10) {
          return '0' + number
      } else{
          return ''+number;
      }
    }
  }

  var minutes = Math.floor(secs/60)%60;
  var hours = Math.floor(secs/(60*60))%24;
  var days = Math.floor(secs/(60*60*24));
  var seconds = Math.floor(secs)%60;

  return (days>0? days+"d " : "")+format(hours)+':'+format(minutes)+':'+format(seconds);
}

,它可以生成以下输出:

  • 5d 02:53:39
  • 4d 22:15:16
  • 03:01:05
  • 00:00:00

I made a simple function, maybe someone can use it

function secsToTime(secs){
  function format(number){
    if(number===0){
      return '00';
    }else {
      if (number < 10) {
          return '0' + number
      } else{
          return ''+number;
      }
    }
  }

  var minutes = Math.floor(secs/60)%60;
  var hours = Math.floor(secs/(60*60))%24;
  var days = Math.floor(secs/(60*60*24));
  var seconds = Math.floor(secs)%60;

  return (days>0? days+"d " : "")+format(hours)+':'+format(minutes)+':'+format(seconds);
}

this can generate the followings outputs:

  • 5d 02:53:39
  • 4d 22:15:16
  • 03:01:05
  • 00:00:00
不知所踪 2024-10-04 02:23:15

如果您想要格式化数字以供查看而不是计算,您可以使用此

function numberFormat( number ){

    var digitCount = (number+"").length;
    var formatedNumber = number+"";
    var ind = digitCount%3 || 3;
    var temparr = formatedNumber.split('');

    if( digitCount > 3 && digitCount <= 6 ){

        temparr.splice(ind,0,',');
        formatedNumber = temparr.join('');

    }else if (digitCount >= 7 && digitCount <= 15) {
        var temparr2 = temparr.slice(0, ind);
        temparr2.push(',');
        temparr2.push(temparr[ind]);
        temparr2.push(temparr[ind + 1]);
        // temparr2.push( temparr[ind + 2] ); 
        if (digitCount >= 7 && digitCount <= 9) {
            temparr2.push(" million");
        } else if (digitCount >= 10 && digitCount <= 12) {
            temparr2.push(" billion");
        } else if (digitCount >= 13 && digitCount <= 15) {
            temparr2.push(" trillion");

        }
        formatedNumber = temparr2.join('');
    }
    return formatedNumber;
}

输入: {Integer} Number

输出: {String} Number

22,870 =>如果数字 22870

2287 万 =>如果数字 2287xxxx(x 可以是任何值)

228,700 亿 =>如果数字 2287xxxxxxx

22,87 万亿 =>如果号码 2287xxxxxxxxx

你就明白了

In case you want to format number for view rather than for calculation you can use this

function numberFormat( number ){

    var digitCount = (number+"").length;
    var formatedNumber = number+"";
    var ind = digitCount%3 || 3;
    var temparr = formatedNumber.split('');

    if( digitCount > 3 && digitCount <= 6 ){

        temparr.splice(ind,0,',');
        formatedNumber = temparr.join('');

    }else if (digitCount >= 7 && digitCount <= 15) {
        var temparr2 = temparr.slice(0, ind);
        temparr2.push(',');
        temparr2.push(temparr[ind]);
        temparr2.push(temparr[ind + 1]);
        // temparr2.push( temparr[ind + 2] ); 
        if (digitCount >= 7 && digitCount <= 9) {
            temparr2.push(" million");
        } else if (digitCount >= 10 && digitCount <= 12) {
            temparr2.push(" billion");
        } else if (digitCount >= 13 && digitCount <= 15) {
            temparr2.push(" trillion");

        }
        formatedNumber = temparr2.join('');
    }
    return formatedNumber;
}

Input: {Integer} Number

Outputs: {String} Number

22,870 => if number 22870

22,87 million => if number 2287xxxx (x can be whatever)

22,87 billion => if number 2287xxxxxxx

22,87 trillion => if number 2287xxxxxxxxxx

You get the idea

痞味浪人 2024-10-04 02:23:15

为了进一步jfriend00的回答(我没有足够的观点来评论),我将他/她的回答扩展到以下内容:

function log(args) {
    var str = "";
    for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === "object") {
            str += JSON.stringify(arguments[i]);
        } else {
            str += arguments[i];
        }
    }
    var div = document.createElement("div");
    div.innerHTML = str;
    document.body.appendChild(div);
}

Number.prototype.addCommas = function (str) {
    if (str === undefined) {
    	str = this;
    }
    
    var parts = (str + "").split("."),
        main = parts[0],
        len = main.length,
        output = "",
        first = main.charAt(0),
        i;
    
    if (first === '-') {
        main = main.slice(1);
        len = main.length;    
    } else {
    	  first = "";
    }
    i = len - 1;
    while(i >= 0) {
        output = main.charAt(i) + output;
        if ((len - i) % 3 === 0 && i > 0) {
            output = "," + output;
        }
        --i;
    }
    // put sign back
    output = first + output;
    // put decimal part back
    if (parts.length > 1) {
        output += "." + parts[1];
    }
    return output;
}

var testCases = [
    1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,
    -1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1
];
 
for (var i = 0; i < testCases.length; i++) {
	log(testCases[i].addCommas());
}
 
/*for (var i = 0; i < testCases.length; i++) {
    log(Number.addCommas(testCases[i]));
}*/

To further jfriend00's answer (I dont't have enough points to comment) I have extended his/her answer to the following:

function log(args) {
    var str = "";
    for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] === "object") {
            str += JSON.stringify(arguments[i]);
        } else {
            str += arguments[i];
        }
    }
    var div = document.createElement("div");
    div.innerHTML = str;
    document.body.appendChild(div);
}

Number.prototype.addCommas = function (str) {
    if (str === undefined) {
    	str = this;
    }
    
    var parts = (str + "").split("."),
        main = parts[0],
        len = main.length,
        output = "",
        first = main.charAt(0),
        i;
    
    if (first === '-') {
        main = main.slice(1);
        len = main.length;    
    } else {
    	  first = "";
    }
    i = len - 1;
    while(i >= 0) {
        output = main.charAt(i) + output;
        if ((len - i) % 3 === 0 && i > 0) {
            output = "," + output;
        }
        --i;
    }
    // put sign back
    output = first + output;
    // put decimal part back
    if (parts.length > 1) {
        output += "." + parts[1];
    }
    return output;
}

var testCases = [
    1, 12, 123, -1234, 12345, 123456, -1234567, 12345678, 123456789,
    -1.1, 12.1, 123.1, 1234.1, -12345.1, -123456.1, -1234567.1, 12345678.1, 123456789.1
];
 
for (var i = 0; i < testCases.length; i++) {
	log(testCases[i].addCommas());
}
 
/*for (var i = 0; i < testCases.length; i++) {
    log(Number.addCommas(testCases[i]));
}*/

请止步禁区 2024-10-04 02:23:15

您可以通过以下方式进行操作:
因此,您不仅可以格式化数字,还可以将要显示的小数位数作为参数传递,您可以设置自定义小数和英里分隔符。

function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
    const roundedNumber = number.toFixed(decimals);
    let integerPart = '', fractionalPart = '';
    if (decimals == 0) {
        integerPart = roundedNumber;
        decimalSeparator = '';
    } else {
        let numberParts = roundedNumber.split('.');
        integerPart = numberParts[0];
        fractionalPart = numberParts[1];
    }
    integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
    return `${integerPart}${decimalSeparator}${fractionalPart}`;
}

使用:

let min = 1556454.0001;
let max = 15556982.9999;
console.time('number format');
for (let i = 0; i < 15000; i++) {
    let randomNumber = Math.random() * (max - min) + min;

    let formated = format(randomNumber, 4, ',', '.'); // formated number

    console.debug('number: ', randomNumber, 'formated: ', formated);
}
console.timeEnd('number format');

You can do it in the following way:
So you will not only format the number but you can also pass as a parameter how many decimal digits to display, you set a custom decimal and mile separator.

function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
    const roundedNumber = number.toFixed(decimals);
    let integerPart = '', fractionalPart = '';
    if (decimals == 0) {
        integerPart = roundedNumber;
        decimalSeparator = '';
    } else {
        let numberParts = roundedNumber.split('.');
        integerPart = numberParts[0];
        fractionalPart = numberParts[1];
    }
    integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
    return `${integerPart}${decimalSeparator}${fractionalPart}`;
}

Use:

let min = 1556454.0001;
let max = 15556982.9999;
console.time('number format');
for (let i = 0; i < 15000; i++) {
    let randomNumber = Math.random() * (max - min) + min;

    let formated = format(randomNumber, 4, ',', '.'); // formated number

    console.debug('number: ', randomNumber, 'formated: ', formated);
}
console.timeEnd('number format');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文