1

私は現在、次のようないくつかのきれいな数字を持っています: 1, 10, 100, 1000, 10000など...

これらの数値をフォーマットしようとしているので、次のように表示されます。

1,00
10,00
100,00
1.000,00
10.000,00

私は遊んでいましn.toFixed(2);たが、探しているフォーマットをサポートしていないようです。

何か案は?

4

5 に答える 5

4

Intl.NumberFormat() をチェックしてください。派手なパンツ プラグインは必要ありません。クロスプラットフォームのサポート。

var number = 3500;
alert(new Intl.NumberFormat().format(number));

「3,500」がポップアップします

于 2013-10-10T23:01:55.430 に答える
1

単純な関数で仕事をしたい場合は、次のものが適しています。

// Format a number n using: 
//   p decimal places (two by default)
//   ts as the thousands separator (comma by default) and
//   dp as the  decimal point (period by default).
//
//   If p < 0 or p > 20 results are implementation dependent.
function formatNumber(n, p, ts, dp) {
  var t = [];
  // Get arguments, set defaults
  if (typeof p  == 'undefined') p  = 2;
  if (typeof ts == 'undefined') ts = ',';
  if (typeof dp == 'undefined') dp = '.';

  // Get number and decimal part of n
  n = Number(n).toFixed(p).split('.');

  // Add thousands separator and decimal point (if requied):
  for (var iLen = n[0].length, i = iLen? iLen % 3 || 3 : 0, j = 0; i <= iLen; i+=3) {
    t.push(n[0].substring(j, i));
    j = i;
  }
  // Insert separators and return result
  return t.join(ts) + (n[1]? dp + n[1] : '');
}


//*
console.log(formatNumber(
    1234567890.567,  // value to format
                 4,  // number of decimal places
               '.',  // thousands separator
                ','  // decimal separator
 ));                 // result: 1.234.567.890,5670
//*/

console.log(formatNumber(
           123.567,  // value to format
                 1   // number of decimal places
 ));                 // result: 123.6

console.log(formatNumber(
         '123.567',  // value to format
                 0   // number of decimal places
 ));                 // result: 123.6

console.log(formatNumber(
               123,  // value to format
                 0   // number of decimal places
 ));                 // result: 123

console.log(formatNumber(
                13,  // value to format
                 2   // number of decimal places
 ));                 // result: 13.00

console.log(formatNumber(
                 0   // value to format
                     // number of decimal places
 ));                 // result: 0.00

console.log(formatNumber(
                     // value to format
                     // number of decimal places
 ));                 // result: NaN

申し訳ありませんが、派手な正規表現やスライス/スプライス配列などはありません。機能する POJS だけです。

于 2013-10-11T00:40:58.103 に答える
1

次のように実行できます。

var nb='1000000000';
var result = nb.replace(/(?:(^\d{1,3})(?=(?:\d{3})*$)|(\d{3}))(?!$)/mg, '$1$2.')+',00';
于 2013-10-10T22:54:16.003 に答える