如何使用JavaScript格式化数字?

时间:2022-09-02 23:21:46

I want to format numbers using JavaScript.

我想用JavaScript格式化数字。

For example:

例如:

10     => 10.00
100    => 100.00
1000   => 1,000.00
10000  => 10,000.00
100000 => 100,000.00

16 个解决方案

#1


109  

If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits, although browser compatibility for the extended options on toLocaleString() is limited.

如果希望使用内置代码,可以使用带有最小umfractionnumbers的toLocaleString(),尽管对toLocaleString()上的扩展选项的浏览器兼容性有限。

var n = 100000;
var value = n.toLocaleString(
  undefined, // leave undefined to use the browser's locale,
             // or use a string like 'en-US' to override it.
  { minimumFractionDigits: 2 }
);
console.log(value);
// In en-US, logs '100,000.00'
// In de-DE, logs '100.000,00'
// In hi-IN, logs '1,00,000.00'

If you're using Node.js, you will need to npm install the intl package.

如果你使用节点。js,需要npm安装intl包。

#2


26  

Due to the bugs found by JasperV — good points! — I have rewritten my old code. I guess I only ever used this for positive values with two decimal places.

由于JasperV发现的bug -很好!-我重写了我的旧代码。我想我只对两个小数点后的正数用过这个。

Depending on what you are trying to achieve, you may want rounding or not, so here are two versions split across that divide.

根据您想要实现的目标,您可能想要舍入或不舍入,因此这里有两个版本在此范围内进行划分。

First up, with rounding.

I've introduced the toFixed() method as it better handles rounding to specific decimal places accurately and is well support. It does slow things down however.

我已经介绍了toFixed()方法,因为它更好地处理精确到特定的小数点位置,并且得到了很好的支持。但它确实会让事情变慢。

This version still detaches the decimal, but using a different method than before. The w|0 part removes the decimal. For more information on that, this is a good answer. This then leaves the remaining integer, stores it in k and then subtracts it again from the original number, leaving the decimal by itself.

这个版本仍然保留小数点,但是使用了不同的方法。w|0部分去掉了小数点。关于这个问题的更多信息,这是一个很好的答案。然后剩下的整数,存储在k中,然后再从原来的数中减去它,剩下的是小数。

Also, if we're to take negative numbers into account, we need to while loop (skipping three digits) until we hit b. This has been calculated to be 1 when dealing with negative numbers to avoid putting something like -,100.00

同样,如果我们要考虑负数,我们需要循环(跳过三位数)直到到达b。当处理负数时,这个被计算为1,以避免输入- 100。00

The rest of the loop is the same as before.

循环的其余部分与以前相同。

function formatThousandsWithRounding(n, dp){
  var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
      u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
      s = ''+k, i = s.length, r = '';
  while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};

In the snippet below you can edit the numbers to test yourself.

在下面的代码片段中,您可以编辑这些数字来测试自己。

function formatThousandsWithRounding(n, dp){
  var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
      u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
      s = ''+k, i = s.length, r = '';
  while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};

var dp;
var createInput = function(v){
  var inp = jQuery('<input class="input" />').val(v);
  var eql = jQuery('<span>&nbsp;=&nbsp;</span>');
  var out = jQuery('<div class="output" />').css('display', 'inline-block');
  var row = jQuery('<div class="row" />');
  row.append(inp).append(eql).append(out);
  inp.keyup(function(){
    out.text(formatThousandsWithRounding(Number(inp.val()), Number(dp.val())));
  });
  inp.keyup();
  jQuery('body').append(row);
  return inp;
};

jQuery(function(){
  var numbers = [
    0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999
  ], inputs = $();
  dp = jQuery('#dp');
  for ( var i=0; i<numbers.length; i++ ) {
    inputs = inputs.add(createInput(numbers[i]));
  }
  dp.on('input change', function(){
    inputs.keyup();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />

Now the other version, without rounding.

This takes a different route and attempts to avoid mathematical calculation (as this can introduce rounding, or rounding errors). If you don't want rounding, then you are only dealing with things as a string i.e. 1000.999 converted to two decimal places will only ever be 1000.99 and not 1001.00.

这采用了不同的方法,并试图避免数学计算(因为这可能引入舍入或舍入错误)。如果你不希望四舍五入,那么你只处理一个字符串,也就是1000。999,转换成两个小数点后的值,只会是1000。99,而不是1001。00。

This method avoids using .split() and RegExp() however, both of which are very slow in comparison. And whilst I learned something new from Michael's answer about toLocaleString, I also was surprised to learn that it is — by quite a way — the slowest method out of them all (at least in Firefox and Chrome; Mac OSX).

但是,这种方法避免使用.split()和RegExp(),这两者相比起来都很慢。当我从Michael关于toLocaleString的回答中了解到一些新的东西时,我也很惊讶地发现,它是其中最慢的方法(至少在Firefox和Chrome中是这样;Mac OSX)。

Using lastIndexOf() we find the possibly existent decimal point, and from there everything else is pretty much the same. Save for the padding with extra 0s where needed. This code is limited to 5 decimal places. Out of my test this was the faster method.

使用lastIndexOf(),我们可以找到可能存在的小数点,从这里我们可以发现几乎所有其他的东西都是一样的。在需要的地方保留额外的0。此代码被限制为5位小数。在我的测试中,这是更快的方法。

var formatThousandsNoRounding = function(n, dp){
  var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
      i = s.lastIndexOf('.'), j = i == -1 ? l : i,
      r = e, d = s.substr(j+1, dp);
  while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
  return s.substr(0, j + 3) + r + 
    (dp ? '.' + d + ( d.length < dp ? 
        ('00000').substr(0, dp - d.length):e):e);
};

var formatThousandsNoRounding = function(n, dp){
  var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
      i = s.lastIndexOf('.'), j = i == -1 ? l : i,
      r = e, d = s.substr(j+1, dp);
  while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
  return s.substr(0, j + 3) + r + 
  	(dp ? '.' + d + ( d.length < dp ? 
    	('00000').substr(0, dp - d.length):e):e);
};

var dp;
var createInput = function(v){
  var inp = jQuery('<input class="input" />').val(v);
  var eql = jQuery('<span>&nbsp;=&nbsp;</span>');
  var out = jQuery('<div class="output" />').css('display', 'inline-block');
  var row = jQuery('<div class="row" />');
  row.append(inp).append(eql).append(out);
  inp.keyup(function(){
    out.text(formatThousandsNoRounding(Number(inp.val()), Number(dp.val())));
  });
  inp.keyup();
  jQuery('body').append(row);
  return inp;
};

jQuery(function(){
  var numbers = [
    0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999
  ], inputs = $();
  dp = jQuery('#dp');
  for ( var i=0; i<numbers.length; i++ ) {
    inputs = inputs.add(createInput(numbers[i]));
  }
  dp.on('input change', function(){
    inputs.keyup();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />

I'll update with an in-page snippet demo shortly, but for now here is a fiddle:

我将很快更新一个页面内的代码片段演示,但是现在这里有一个小提琴:

https://jsfiddle.net/bv2ort0a/2/

https://jsfiddle.net/bv2ort0a/2/



Old Method

Why use RegExp for this? — don't use a hammer when a toothpick will do i.e. use string manipulation:

为什么要使用RegExp ?-当牙签可以使用时,不要使用锤子,例如:

var formatThousands = function(n, dp){
  var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
  while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + 
    (d ? '.' + Math.round(d * Math.pow(10, dp || 2)) : '');
};

walk through

formatThousands( 1000000.42 );

First strip off decimal:

首先去掉小数:

s = '1000000', d = ~ 0.42

Work backwards from the end of the string:

从弦的末端向后工作:

',' + '000'
',' + '000' + ',000'

Finalise by adding the leftover prefix and the decimal suffix (with rounding to dp no. decimal points):

最后加入剩余的前缀和十进制后缀(四舍五入到dp编号)。小数点):

'1' + ',000,000' + '.42'

fiddlesticks

http://jsfiddle.net/XC3sS/

http://jsfiddle.net/XC3sS/

#3


23  

Use

使用

num = num.toFixed(2);

Where 2 is the number of decimal places

小数点的位数是2

Edit:

编辑:

Here's the function to format number as you want

这里有一个函数来格式化数字

function formatNumber(number)
{
    number = number.toFixed(2) + '';
    x = number.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Sorce: www.mredkj.com

比照:www.mredkj.com

#4


23  

Short solution:

短期解决方案:

var n = 1234567890;
String(n).replace(/(.)(?=(\d{3})+$)/g,'$1,')
// "1,234,567,890"

#5


13  

On browsers that support the ECMAScript® 2016 Internationalization API Specification (ECMA-402), you can use an Intl.NumberFormat instance:

浏览器支持ECMAScript®2016国际化API规范(ecma - 402),您可以使用一个Intl。NumberFormat实例:

var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
                           // 42.000.000 in many other locales

if (typeof Intl === "undefined" || !Intl.NumberFormat) {
  console.log("This browser doesn't support Intl.NumberFormat");
} else {
  var nf = Intl.NumberFormat();
  var x = 42000000;
  console.log(nf.format(x)); // 42,000,000 in many locales
                             // 42.000.000 in many other locales
}

#6


7  

I think with this jQuery-numberformatter you could solve your problem.

我认为有了这个jQuery-numberformatter,你就可以解决你的问题。

$("#salary").blur(function(){
   $(this).parseNumber({format:"#,###.00", locale:"us"});
   $(this).formatNumber({format:"#,###.00", locale:"us"});
});

Of course, this is assuming that you don't have problem with using jQuery in your project.

当然,这是假设您在项目中使用jQuery没有问题。

#7


4  

Use the Number function toFixed and this function to add the commas.

使用要固定的Number函数和这个函数来添加逗号。

function addCommas(nStr)
{
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
n = 10000;
r = n.toFixed(2); //10000.00

addCommas(r); // 10,000.00

http://www.mredkj.com/javascript/numberFormat.html

http://www.mredkj.com/javascript/numberFormat.html

#8


3  

function numberWithCommas(x) {
  x=String(x).toString();
  var afterPoint = '';
  if(x.indexOf('.') > 0)
     afterPoint = x.substring(x.indexOf('.'),x.length);
  x = Math.floor(x);
  x=x.toString();
  var lastThree = x.substring(x.length-3);
  var otherNumbers = x.substring(0,x.length-3);
  if(otherNumbers != '')
      lastThree = ',' + lastThree;
  return otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
}

console.log(numberWithCommas(100000));
console.log(numberWithCommas(10000000));

Output

1,00,000
1,00,00,000

00000 00000 1 00

#9


3  

This is an article about your problem. Adding a thousands-seperator is not built in to JavaScript, so you'll have to write your own function like this (example taken from the linked page):

这是一篇关于你的问题的文章。添加一个千分器并没有内置到JavaScript中,因此您必须编写自己的函数,如以下所示(示例来自链接页面):

function addSeperator(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

#10


2  

Or you could use the sugar.js library, and the format method:

或者你可以用糖。js库,格式方法:

format( place = 0 , thousands = ',' , decimal = '.' ) Formats the number to a readable string. If place is undefined, will automatically determine the place. thousands is the character used for the thousands separator. decimal is the character used for the decimal point.

格式(place = 0, thousand = ',', decimal = ')。)将数字格式化为可读字符串。如果地点没有定义,将自动确定地点。千位字符用于千位分隔符。十进制是小数点的字符。

Examples:

例子:

(56782).format() > "56,782"
(56782).format(2) > "56,782.00"
(4388.43).format(2, ' ') > "4 388.43"
(4388.43).format(3, '.', ',') > "4.388,430"

#11


2  

If you are looking for a formatting with limit to three significant digits, for example:

如果您正在寻找限制为3位有效数字的格式,例如:

1,23,45,67,890.123

Use:

使用:

number.toLocaleString('en-IN');

Working Example:

工作的例子:

let number = 1234567890.123; 

document.write(number.toLocaleString('en-IN'));

Tested in Chrome v60.0.3112.113

测试在Chrome v60.0.3112.113

Source: Number.prototype.toLocaleString() | MDN

来源:Number.prototype.toLocaleString()| MDN

#12


1  

This will get you your comma seperated values as well as add the fixed notation to the end.

这将得到逗号分隔的值,并在末尾添加固定的符号。

    nStr="1000";
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    commaSeperated = x1 + x2 + ".00";
    alert(commaSeperated);

Source

#13


1  

Let me also throw my solution in here. I've commented each line for ease of reading and also provided some examples, so it may look big.

让我把溶液扔到这里。我已经注释了每一行,以方便阅读,也提供了一些示例,所以它看起来可能很大。

function format(number) {

    var decimalSeparator = ".";
    var thousandSeparator = ",";

    // make sure we have a string
    var result = String(number);

    // split the number in the integer and decimals, if any
    var parts = result.split(decimalSeparator);

    // if we don't have decimals, add .00
    if (!parts[1]) {
      parts[1] = "00";
    }
  
    // reverse the string (1719 becomes 9171)
    result = parts[0].split("").reverse().join("");

    // add thousand separator each 3 characters, except at the end of the string
    result = result.replace(/(\d{3}(?!$))/g, "$1" + thousandSeparator);

    // reverse back the integer and replace the original integer
    parts[0] = result.split("").reverse().join("");

    // recombine integer with decimals
    return parts.join(decimalSeparator);
}

document.write("10 => " + format(10) + "<br/>");
document.write("100 => " + format(100) + "<br/>");
document.write("1000 => " + format(1000) + "<br/>");
document.write("10000 => " + format(10000) + "<br/>");
document.write("100000 => " + format(100000) + "<br/>");
document.write("100000.22 => " + format(100000.22) + "<br/>");

#14


0  

If you're using jQuery, you could use the format or number format plugins.

如果使用jQuery,可以使用格式或数字格式插件。

#15


0  

 function formatNumber1(number) {
  var comma = ',',
      string = Math.max(0, number).toFixed(0),
      length = string.length,
      end = /^\d{4,}$/.test(string) ? length % 3 : 0;
  return (end ? string.slice(0, end) + comma : '') + string.slice(end).replace(/(\d{3})(?=\d)/g, '$1' + comma);
 }

 function formatNumber2(number) {
  return Math.max(0, number).toFixed(0).replace(/(?=(?:\d{3})+$)(?!^)/g, ',');
 }

Source: http://jsperf.com/number-format

来源:http://jsperf.com/number-format

#16


0  

This is about 3 times faster version of the accepted answer. It doesn't create array and avoids object creation and string concatenation for whole numbers at the end. This might be useful if you render lots of values e.g. in a table.

这是公认答案的3倍快。它不创建数组,并且避免了对象创建和字符串连接。如果你在表格中呈现很多值,这可能会很有用。

function addThousandSeparators(number) {
    var whole, fraction
    var decIndex = number.lastIndexOf('.')
    if (decIndex > 0) {
        whole = number.substr(0, decIndex)
        fraction = number.substr(decIndex)
    } else {
        whole = number
    }
    var rgx = /(\d+)(\d{3})/
    while (rgx.test(whole)) {
        whole = whole.replace(rgx, '$1' + ',' + '$2')
    }
    return fraction ? whole + fraction : whole
}

#1


109  

If you want to use built-in code, you can use toLocaleString() with minimumFractionDigits, although browser compatibility for the extended options on toLocaleString() is limited.

如果希望使用内置代码,可以使用带有最小umfractionnumbers的toLocaleString(),尽管对toLocaleString()上的扩展选项的浏览器兼容性有限。

var n = 100000;
var value = n.toLocaleString(
  undefined, // leave undefined to use the browser's locale,
             // or use a string like 'en-US' to override it.
  { minimumFractionDigits: 2 }
);
console.log(value);
// In en-US, logs '100,000.00'
// In de-DE, logs '100.000,00'
// In hi-IN, logs '1,00,000.00'

If you're using Node.js, you will need to npm install the intl package.

如果你使用节点。js,需要npm安装intl包。

#2


26  

Due to the bugs found by JasperV — good points! — I have rewritten my old code. I guess I only ever used this for positive values with two decimal places.

由于JasperV发现的bug -很好!-我重写了我的旧代码。我想我只对两个小数点后的正数用过这个。

Depending on what you are trying to achieve, you may want rounding or not, so here are two versions split across that divide.

根据您想要实现的目标,您可能想要舍入或不舍入,因此这里有两个版本在此范围内进行划分。

First up, with rounding.

I've introduced the toFixed() method as it better handles rounding to specific decimal places accurately and is well support. It does slow things down however.

我已经介绍了toFixed()方法,因为它更好地处理精确到特定的小数点位置,并且得到了很好的支持。但它确实会让事情变慢。

This version still detaches the decimal, but using a different method than before. The w|0 part removes the decimal. For more information on that, this is a good answer. This then leaves the remaining integer, stores it in k and then subtracts it again from the original number, leaving the decimal by itself.

这个版本仍然保留小数点,但是使用了不同的方法。w|0部分去掉了小数点。关于这个问题的更多信息,这是一个很好的答案。然后剩下的整数,存储在k中,然后再从原来的数中减去它,剩下的是小数。

Also, if we're to take negative numbers into account, we need to while loop (skipping three digits) until we hit b. This has been calculated to be 1 when dealing with negative numbers to avoid putting something like -,100.00

同样,如果我们要考虑负数,我们需要循环(跳过三位数)直到到达b。当处理负数时,这个被计算为1,以避免输入- 100。00

The rest of the loop is the same as before.

循环的其余部分与以前相同。

function formatThousandsWithRounding(n, dp){
  var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
      u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
      s = ''+k, i = s.length, r = '';
  while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};

In the snippet below you can edit the numbers to test yourself.

在下面的代码片段中,您可以编辑这些数字来测试自己。

function formatThousandsWithRounding(n, dp){
  var w = n.toFixed(dp), k = w|0, b = n < 0 ? 1 : 0,
      u = Math.abs(w-k), d = (''+u.toFixed(dp)).substr(2, dp),
      s = ''+k, i = s.length, r = '';
  while ( (i-=3) > b ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + (d ? '.'+d: '');
};

var dp;
var createInput = function(v){
  var inp = jQuery('<input class="input" />').val(v);
  var eql = jQuery('<span>&nbsp;=&nbsp;</span>');
  var out = jQuery('<div class="output" />').css('display', 'inline-block');
  var row = jQuery('<div class="row" />');
  row.append(inp).append(eql).append(out);
  inp.keyup(function(){
    out.text(formatThousandsWithRounding(Number(inp.val()), Number(dp.val())));
  });
  inp.keyup();
  jQuery('body').append(row);
  return inp;
};

jQuery(function(){
  var numbers = [
    0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999
  ], inputs = $();
  dp = jQuery('#dp');
  for ( var i=0; i<numbers.length; i++ ) {
    inputs = inputs.add(createInput(numbers[i]));
  }
  dp.on('input change', function(){
    inputs.keyup();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />

Now the other version, without rounding.

This takes a different route and attempts to avoid mathematical calculation (as this can introduce rounding, or rounding errors). If you don't want rounding, then you are only dealing with things as a string i.e. 1000.999 converted to two decimal places will only ever be 1000.99 and not 1001.00.

这采用了不同的方法,并试图避免数学计算(因为这可能引入舍入或舍入错误)。如果你不希望四舍五入,那么你只处理一个字符串,也就是1000。999,转换成两个小数点后的值,只会是1000。99,而不是1001。00。

This method avoids using .split() and RegExp() however, both of which are very slow in comparison. And whilst I learned something new from Michael's answer about toLocaleString, I also was surprised to learn that it is — by quite a way — the slowest method out of them all (at least in Firefox and Chrome; Mac OSX).

但是,这种方法避免使用.split()和RegExp(),这两者相比起来都很慢。当我从Michael关于toLocaleString的回答中了解到一些新的东西时,我也很惊讶地发现,它是其中最慢的方法(至少在Firefox和Chrome中是这样;Mac OSX)。

Using lastIndexOf() we find the possibly existent decimal point, and from there everything else is pretty much the same. Save for the padding with extra 0s where needed. This code is limited to 5 decimal places. Out of my test this was the faster method.

使用lastIndexOf(),我们可以找到可能存在的小数点,从这里我们可以发现几乎所有其他的东西都是一样的。在需要的地方保留额外的0。此代码被限制为5位小数。在我的测试中,这是更快的方法。

var formatThousandsNoRounding = function(n, dp){
  var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
      i = s.lastIndexOf('.'), j = i == -1 ? l : i,
      r = e, d = s.substr(j+1, dp);
  while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
  return s.substr(0, j + 3) + r + 
    (dp ? '.' + d + ( d.length < dp ? 
        ('00000').substr(0, dp - d.length):e):e);
};

var formatThousandsNoRounding = function(n, dp){
  var e = '', s = e+n, l = s.length, b = n < 0 ? 1 : 0,
      i = s.lastIndexOf('.'), j = i == -1 ? l : i,
      r = e, d = s.substr(j+1, dp);
  while ( (j-=3) > b ) { r = ',' + s.substr(j, 3) + r; }
  return s.substr(0, j + 3) + r + 
  	(dp ? '.' + d + ( d.length < dp ? 
    	('00000').substr(0, dp - d.length):e):e);
};

var dp;
var createInput = function(v){
  var inp = jQuery('<input class="input" />').val(v);
  var eql = jQuery('<span>&nbsp;=&nbsp;</span>');
  var out = jQuery('<div class="output" />').css('display', 'inline-block');
  var row = jQuery('<div class="row" />');
  row.append(inp).append(eql).append(out);
  inp.keyup(function(){
    out.text(formatThousandsNoRounding(Number(inp.val()), Number(dp.val())));
  });
  inp.keyup();
  jQuery('body').append(row);
  return inp;
};

jQuery(function(){
  var numbers = [
    0, 99.999, -1000, -1000000, 1000000.42, -1000000.57, -1000000.999
  ], inputs = $();
  dp = jQuery('#dp');
  for ( var i=0; i<numbers.length; i++ ) {
    inputs = inputs.add(createInput(numbers[i]));
  }
  dp.on('input change', function(){
    inputs.keyup();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="dp" type="range" min="0" max="5" step="1" value="2" title="number of decimal places?" />

I'll update with an in-page snippet demo shortly, but for now here is a fiddle:

我将很快更新一个页面内的代码片段演示,但是现在这里有一个小提琴:

https://jsfiddle.net/bv2ort0a/2/

https://jsfiddle.net/bv2ort0a/2/



Old Method

Why use RegExp for this? — don't use a hammer when a toothpick will do i.e. use string manipulation:

为什么要使用RegExp ?-当牙签可以使用时,不要使用锤子,例如:

var formatThousands = function(n, dp){
  var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
  while ( (i -= 3) > 0 ) { r = ',' + s.substr(i, 3) + r; }
  return s.substr(0, i + 3) + r + 
    (d ? '.' + Math.round(d * Math.pow(10, dp || 2)) : '');
};

walk through

formatThousands( 1000000.42 );

First strip off decimal:

首先去掉小数:

s = '1000000', d = ~ 0.42

Work backwards from the end of the string:

从弦的末端向后工作:

',' + '000'
',' + '000' + ',000'

Finalise by adding the leftover prefix and the decimal suffix (with rounding to dp no. decimal points):

最后加入剩余的前缀和十进制后缀(四舍五入到dp编号)。小数点):

'1' + ',000,000' + '.42'

fiddlesticks

http://jsfiddle.net/XC3sS/

http://jsfiddle.net/XC3sS/

#3


23  

Use

使用

num = num.toFixed(2);

Where 2 is the number of decimal places

小数点的位数是2

Edit:

编辑:

Here's the function to format number as you want

这里有一个函数来格式化数字

function formatNumber(number)
{
    number = number.toFixed(2) + '';
    x = number.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Sorce: www.mredkj.com

比照:www.mredkj.com

#4


23  

Short solution:

短期解决方案:

var n = 1234567890;
String(n).replace(/(.)(?=(\d{3})+$)/g,'$1,')
// "1,234,567,890"

#5


13  

On browsers that support the ECMAScript® 2016 Internationalization API Specification (ECMA-402), you can use an Intl.NumberFormat instance:

浏览器支持ECMAScript®2016国际化API规范(ecma - 402),您可以使用一个Intl。NumberFormat实例:

var nf = Intl.NumberFormat();
var x = 42000000;
console.log(nf.format(x)); // 42,000,000 in many locales
                           // 42.000.000 in many other locales

if (typeof Intl === "undefined" || !Intl.NumberFormat) {
  console.log("This browser doesn't support Intl.NumberFormat");
} else {
  var nf = Intl.NumberFormat();
  var x = 42000000;
  console.log(nf.format(x)); // 42,000,000 in many locales
                             // 42.000.000 in many other locales
}

#6


7  

I think with this jQuery-numberformatter you could solve your problem.

我认为有了这个jQuery-numberformatter,你就可以解决你的问题。

$("#salary").blur(function(){
   $(this).parseNumber({format:"#,###.00", locale:"us"});
   $(this).formatNumber({format:"#,###.00", locale:"us"});
});

Of course, this is assuming that you don't have problem with using jQuery in your project.

当然,这是假设您在项目中使用jQuery没有问题。

#7


4  

Use the Number function toFixed and this function to add the commas.

使用要固定的Number函数和这个函数来添加逗号。

function addCommas(nStr)
{
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}
n = 10000;
r = n.toFixed(2); //10000.00

addCommas(r); // 10,000.00

http://www.mredkj.com/javascript/numberFormat.html

http://www.mredkj.com/javascript/numberFormat.html

#8


3  

function numberWithCommas(x) {
  x=String(x).toString();
  var afterPoint = '';
  if(x.indexOf('.') > 0)
     afterPoint = x.substring(x.indexOf('.'),x.length);
  x = Math.floor(x);
  x=x.toString();
  var lastThree = x.substring(x.length-3);
  var otherNumbers = x.substring(0,x.length-3);
  if(otherNumbers != '')
      lastThree = ',' + lastThree;
  return otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
}

console.log(numberWithCommas(100000));
console.log(numberWithCommas(10000000));

Output

1,00,000
1,00,00,000

00000 00000 1 00

#9


3  

This is an article about your problem. Adding a thousands-seperator is not built in to JavaScript, so you'll have to write your own function like this (example taken from the linked page):

这是一篇关于你的问题的文章。添加一个千分器并没有内置到JavaScript中,因此您必须编写自己的函数,如以下所示(示例来自链接页面):

function addSeperator(nStr){
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
  }
  return x1 + x2;
}

#10


2  

Or you could use the sugar.js library, and the format method:

或者你可以用糖。js库,格式方法:

format( place = 0 , thousands = ',' , decimal = '.' ) Formats the number to a readable string. If place is undefined, will automatically determine the place. thousands is the character used for the thousands separator. decimal is the character used for the decimal point.

格式(place = 0, thousand = ',', decimal = ')。)将数字格式化为可读字符串。如果地点没有定义,将自动确定地点。千位字符用于千位分隔符。十进制是小数点的字符。

Examples:

例子:

(56782).format() > "56,782"
(56782).format(2) > "56,782.00"
(4388.43).format(2, ' ') > "4 388.43"
(4388.43).format(3, '.', ',') > "4.388,430"

#11


2  

If you are looking for a formatting with limit to three significant digits, for example:

如果您正在寻找限制为3位有效数字的格式,例如:

1,23,45,67,890.123

Use:

使用:

number.toLocaleString('en-IN');

Working Example:

工作的例子:

let number = 1234567890.123; 

document.write(number.toLocaleString('en-IN'));

Tested in Chrome v60.0.3112.113

测试在Chrome v60.0.3112.113

Source: Number.prototype.toLocaleString() | MDN

来源:Number.prototype.toLocaleString()| MDN

#12


1  

This will get you your comma seperated values as well as add the fixed notation to the end.

这将得到逗号分隔的值,并在末尾添加固定的符号。

    nStr="1000";
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    commaSeperated = x1 + x2 + ".00";
    alert(commaSeperated);

Source

#13


1  

Let me also throw my solution in here. I've commented each line for ease of reading and also provided some examples, so it may look big.

让我把溶液扔到这里。我已经注释了每一行,以方便阅读,也提供了一些示例,所以它看起来可能很大。

function format(number) {

    var decimalSeparator = ".";
    var thousandSeparator = ",";

    // make sure we have a string
    var result = String(number);

    // split the number in the integer and decimals, if any
    var parts = result.split(decimalSeparator);

    // if we don't have decimals, add .00
    if (!parts[1]) {
      parts[1] = "00";
    }
  
    // reverse the string (1719 becomes 9171)
    result = parts[0].split("").reverse().join("");

    // add thousand separator each 3 characters, except at the end of the string
    result = result.replace(/(\d{3}(?!$))/g, "$1" + thousandSeparator);

    // reverse back the integer and replace the original integer
    parts[0] = result.split("").reverse().join("");

    // recombine integer with decimals
    return parts.join(decimalSeparator);
}

document.write("10 => " + format(10) + "<br/>");
document.write("100 => " + format(100) + "<br/>");
document.write("1000 => " + format(1000) + "<br/>");
document.write("10000 => " + format(10000) + "<br/>");
document.write("100000 => " + format(100000) + "<br/>");
document.write("100000.22 => " + format(100000.22) + "<br/>");

#14


0  

If you're using jQuery, you could use the format or number format plugins.

如果使用jQuery,可以使用格式或数字格式插件。

#15


0  

 function formatNumber1(number) {
  var comma = ',',
      string = Math.max(0, number).toFixed(0),
      length = string.length,
      end = /^\d{4,}$/.test(string) ? length % 3 : 0;
  return (end ? string.slice(0, end) + comma : '') + string.slice(end).replace(/(\d{3})(?=\d)/g, '$1' + comma);
 }

 function formatNumber2(number) {
  return Math.max(0, number).toFixed(0).replace(/(?=(?:\d{3})+$)(?!^)/g, ',');
 }

Source: http://jsperf.com/number-format

来源:http://jsperf.com/number-format

#16


0  

This is about 3 times faster version of the accepted answer. It doesn't create array and avoids object creation and string concatenation for whole numbers at the end. This might be useful if you render lots of values e.g. in a table.

这是公认答案的3倍快。它不创建数组,并且避免了对象创建和字符串连接。如果你在表格中呈现很多值,这可能会很有用。

function addThousandSeparators(number) {
    var whole, fraction
    var decIndex = number.lastIndexOf('.')
    if (decIndex > 0) {
        whole = number.substr(0, decIndex)
        fraction = number.substr(decIndex)
    } else {
        whole = number
    }
    var rgx = /(\d+)(\d{3})/
    while (rgx.test(whole)) {
        whole = whole.replace(rgx, '$1' + ',' + '$2')
    }
    return fraction ? whole + fraction : whole
}