How do I format numbers using JavaScript?

2019-01-01 13:22发布

I want to format numbers using JavaScript.

For example:

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

标签: javascript
16条回答
牵手、夕阳
2楼-- · 2019-01-01 13:35

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

$("#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.

查看更多
与君花间醉酒
3楼-- · 2019-01-01 13:39
 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

查看更多
谁念西风独自凉
4楼-- · 2019-01-01 13:40

Short solution:

var n = 1234567890;
String(n).replace(/(.)(?=(\d{3})+$)/g,'$1,')
// "1,234,567,890"
查看更多
美炸的是我
5楼-- · 2019-01-01 13:42

Use

num = num.toFixed(2);

Where 2 is the number of decimal places

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

查看更多
刘海飞了
6楼-- · 2019-01-01 13:44

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

查看更多
明月照影归
7楼-- · 2019-01-01 13:46

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.

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.

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.

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

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.

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).

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.

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/



Old Method

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

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):

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

fiddlesticks

http://jsfiddle.net/XC3sS/

查看更多
登录 后发表回答