2243

JavaScript で価格をフォーマットしたいと思います。引数としてa を取り、次のようにフォーマットさfloatれた a を返す関数が欲しいです:string

"$ 2,500.00"

これを行う最善の方法は何ですか?

4

69 に答える 69

2301

Intl.NumberFormat

JavaScript には数値フォーマッター (国際化 API の一部) があります。

// Create our number formatter.
var formatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',

  // These options are needed to round to whole numbers if that's what you want.
  //minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)
  //maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)
});

formatter.format(2500); /* $2,500.00 */

undefined最初の引数 (例) の代わりに使用して'en-US'、システム ロケール (コードがブラウザーで実行されている場合のユーザー ロケール) を使用します。ロケールコードの詳細説明

通貨コードの一覧は次のとおりです。

Intl.NumberFormat vs Number.prototype.toLocaleString

これを古いものと比較する最後のメモ。toLocaleString. どちらも基本的に同じ機能を提供します。ただし、古い化身 (Intl 以前) の toLocaleString は、実際には locales をサポートしていません。システム ロケールを使用します。そのため、古いブラウザーをデバッグするときは、正しいバージョンを使用していることを確認してください ( MDN は、の存在を確認することを提案してIntlいます)。古いブラウザを気にしない場合やshimを使用するだけの場合は、これについてまったく心配する必要はありません。

また、単一のアイテムの場合、両方のパフォーマンスは同じですが、フォーマットする数値が多い場合は、使用しIntl.NumberFormatた方が ~70 倍速くなります。したがって、通常は、Intl.NumberFormatページの読み込みごとに 1 回だけ使用してインスタンス化することをお勧めします。とにかく、これは同等の使用法ですtoLocaleString

(2500).toLocaleString('en-US', {
  style: 'currency',
  currency: 'USD',
}); /* $2,500.00 */

ブラウザーのサポートと Node.js に関する注意事項

  • 現在、ブラウザのサポートはもはや問題ではなく、世界で 98%、米国で 99%、EU で 99% 以上のサポートが提供されています。
  • 本当に必要な場合は、化石化したブラウザー ( Internet Explorer 8など) でサポートするためのshimがあります。
  • v13 より前の Node.js は、標準でのみサポートen-USされています。解決策の 1 つは、 full-icuをインストールすることです。詳細については、こちらを参照してください。
  • 詳細については、CanIUseをご覧ください。
于 2013-04-26T10:09:56.210 に答える
1928

Number.prototype.toFixed

このソリューションは、すべての主要なブラウザーと互換性があります。

  const profits = 2489.8237;

  profits.toFixed(3) // Returns 2489.824 (rounds up)
  profits.toFixed(2) // Returns 2489.82
  profits.toFixed(7) // Returns 2489.8237000 (pads the decimals)

通貨記号 (例: "$" + profits.toFixed(2)) を追加するだけで、金額がドルになります。

カスタム機能

各桁の間で を使用する必要がある場合は、次の,関数を使用できます。

function formatMoney(number, decPlaces, decSep, thouSep) {
    decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
    decSep = typeof decSep === "undefined" ? "." : decSep;
    thouSep = typeof thouSep === "undefined" ? "," : thouSep;
    var sign = number < 0 ? "-" : "";
    var i = String(parseInt(number = Math.abs(Number(number) || 0).toFixed(decPlaces)));
    var j = (j = i.length) > 3 ? j % 3 : 0;

    return sign +
        (j ? i.substr(0, j) + thouSep : "") +
        i.substr(j).replace(/(\decSep{3})(?=\decSep)/g, "$1" + thouSep) +
        (decPlaces ? decSep + Math.abs(number - i).toFixed(decPlaces).slice(2) : "");
}

document.getElementById("b").addEventListener("click", event => {
  document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);
});
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label>
<br />
<button id="b">Get Output</button>
<p id="x">(press button to get output)</p>

次のように使用します。

(123456789.12345).formatMoney(2, ".", ",");

常に「.」を使用する場合 および ',' である場合、これらをメソッド呼び出しから除外することができ、メソッドによってデフォルトで設定されます。

(123456789.12345).formatMoney(2);

formatMoney文化が反転した 2 つのシンボル (つまり、ヨーロッパ人) を持っていて、デフォルトを使用したい場合は、メソッドに次の 2 行を貼り付けます。

    d = d == undefined ? "," : d,
    t = t == undefined ? "." : t,

カスタム関数 (ES6)

最新の ECMAScript 構文を (つまり、Babel を介して) 使用できる場合は、代わりにこの単純な関数を使用できます。

function formatMoney(amount, decimalCount = 2, decimal = ".", thousands = ",") {
  try {
    decimalCount = Math.abs(decimalCount);
    decimalCount = isNaN(decimalCount) ? 2 : decimalCount;

    const negativeSign = amount < 0 ? "-" : "";

    let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString();
    let j = (i.length > 3) ? i.length % 3 : 0;

    return
      negativeSign +
      (j ? i.substr(0, j) + thousands : '') +
      i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) +
      (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : "");
  } catch (e) {
    console.log(e)
  }
};

document.getElementById("b").addEventListener("click", event => {
  document.getElementById("x").innerText = "Result was: " + formatMoney(document.getElementById("d").value);
});
<label>Insert your amount: <input id="d" type="text" placeholder="Cash amount" /></label>
<br />
<button id="b">Get Output</button>
<p id="x">(press button to get output)</p>

于 2008-09-29T15:12:32.693 に答える
1448

短くて速い解決策 (どこでも使える!)

(12345.67).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');  // 12,345.67

このソリューションの背後にあるアイデアは、一致したセクションを最初の一致とコンマに置き換えることです'$&,'。照合は、先読みアプローチを使用して行われます。この表現は、 「3 つの数値セット (1 つ以上) とドットのシーケンスが後に続く場合、数値に一致する」 と読むことができます。

テスト:

1        --> "1.00"
12       --> "12.00"
123      --> "123.00"
1234     --> "1,234.00"
12345    --> "12,345.00"
123456   --> "123,456.00"
1234567  --> "1,234,567.00"
12345.67 --> "12,345.67"

デモ: http://jsfiddle.net/hAfMM/9571/


拡張ショート ソリューション

また、オブジェクトのプロトタイプを拡張して、任意の小数点以下の桁数と数値グループのサイズのNumberサポートを追加することもできます。[0 .. n][0 .. x]

/**
 * Number.prototype.format(n, x)
 * 
 * @param integer n: length of decimal
 * @param integer x: length of sections
 */
Number.prototype.format = function(n, x) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')';
    return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,');
};

1234..format();           // "1,234"
12345..format(2);         // "12,345.00"
123456.7.format(3, 2);    // "12,34,56.700"
123456.789.format(2, 4);  // "12,3456.79"

デモ/テスト: http://jsfiddle.net/hAfMM/435/


超拡張ショートソリューション

この超拡張バージョンでは、さまざまな区切り文字タイプを設定できます。

/**
 * Number.prototype.format(n, x, s, c)
 * 
 * @param integer n: length of decimal
 * @param integer x: length of whole part
 * @param mixed   s: sections delimiter
 * @param mixed   c: decimal delimiter
 */
Number.prototype.format = function(n, x, s, c) {
    var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\D' : '$') + ')',
        num = this.toFixed(Math.max(0, ~~n));

    return (c ? num.replace('.', c) : num).replace(new RegExp(re, 'g'), '$&' + (s || ','));
};

12345678.9.format(2, 3, '.', ',');  // "12.345.678,90"
123456.789.format(4, 4, ' ', ':');  // "12 3456:7890"
12345678.9.format(0, 3, '-');       // "12-345-679"

デモ/テスト: http://jsfiddle.net/hAfMM/612/

于 2013-01-20T19:25:37.683 に答える
328

JavaScript Numberオブジェクトを見て、それが役立つかどうかを確認してください。

  • toLocaleString()場所固有の桁区切り記号を使用して数値をフォーマットします。
  • toFixed()数値を特定の小数点以下の桁数に丸めます。

これらを同時に使用するには、両方とも文字列を出力するため、値の型を数値に戻す必要があります。

例:

Number((someNumber).toFixed(1)).toLocaleString()

編集

toLocaleString を直接使用するだけでよく、数値に再キャストする必要はありません。

someNumber.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});

複数の番号

同様に数値を頻繁にフォーマットする必要がある場合は、再利用のために特定のオブジェクトを作成できます。ドイツ語 (スイス) の場合:

const money = new Intl.NumberFormat('de-CH',
  { style:'currency', currency: 'CHF' });
const percent = new Intl.NumberFormat('de-CH',
  { style:'percent', maximumFractionDigits: 1, signDisplay: "always"});

次のように使用できます。

money.format(1234.50); // output CHF 1'234.50
percent.format(0.083);  // output +8.3%

かなり気の利いた。

于 2008-09-29T15:14:47.167 に答える
170

以下は、Patrick Desjardins (別名 Daok)のコードに、少しコメントを追加し、いくつかの小さな変更を加えたものです。

/*
decimal_sep: character used as decimal separator, it defaults to '.' when omitted
thousands_sep: char used as thousands separator, it defaults to ',' when omitted
*/
Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep)
{
   var n = this,
   c = isNaN(decimals) ? 2 : Math.abs(decimals), // If decimal is zero we must take it. It means the user does not want to show any decimal
   d = decimal_sep || '.', // If no decimal separator is passed, we use the dot as default decimal separator (we MUST use a decimal separator)

   /*
   According to [https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]
   the fastest way to check for not defined parameter is to use typeof value === 'undefined'
   rather than doing value === undefined.
   */
   t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, // If you don't want to use a thousands separator you can pass empty string as thousands_sep value

   sign = (n < 0) ? '-' : '',

   // Extracting the absolute value of the integer part of the number and converting to string
   i = parseInt(n = Math.abs(n).toFixed(c)) + '',

   j = ((j = i.length) > 3) ? j % 3 : 0;
   return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');
}

そしてここでいくつかのテスト:

// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert(123456789.67392.toMoney() + '\n' + 123456789.67392.toMoney(3) + '\n' + 123456789.67392.toMoney(0) + '\n' + (123456).toMoney() + '\n' + (123456).toMoney(0) + '\n' + 89.67392.toMoney() + '\n' + (89).toMoney());

// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)
alert((-123456789.67392).toMoney() + '\n' + (-123456789.67392).toMoney(-3));

マイナーな変更は次のとおりです。

  1. Math.abs(decimals)ない場合にのみ行うように少し移動しましたNaN

  2. decimal_sepこれ以上空の文字列にすることはできません (ある種の小数点記号が必須です)

  3. 引数が JavaScript 関数に送信されていないかどうかを判断する最善の方法でtypeof thousands_sep === 'undefined'提案されているように使用します

  4. (+n || 0)thisNumberオブジェクトなので必要ありません

JSFiddle

于 2010-05-19T14:48:54.860 に答える
140

金額が数値の場合、たとえば-123

amount.toLocaleString('en-US', { style: 'currency', currency: 'USD' });

文字列を生成します"-$123.00"

完全な作業を次に示します。

于 2014-11-04T21:09:38.167 に答える
129

accounting.jsは、数値、金額、および通貨の書式設定用の小さな JavaScript ライブラリです。

于 2011-09-01T05:46:10.100 に答える
113

私が見た中で最高の JavaScript マネーフォーマッタは次のとおりです。

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) {
    var n = this,
        decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces,
        decSeparator = decSeparator == undefined ? "." : decSeparator,
        thouSeparator = thouSeparator == undefined ? "," : thouSeparator,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;
    return sign + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};

再フォーマットされ、ここから借用されました:数値を通貨文字列としてフォーマットする方法

独自の通貨指定子 ($上で使用したもの) を提供する必要があります。

次のように呼び出します (ただし、引数のデフォルトは 2、コンマ、およびピリオドなので、お好みであれば引数を指定する必要はありません):

var myMoney = 3543.75873;
var formattedMoney = '$' + myMoney.formatMoney(2, ',', '.'); // "$3,543.76"
于 2012-02-16T20:42:10.293 に答える
86

楽しみのために、別の試みがあります:

function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    return "$" + p[0].split("").reverse().reduce(function(acc, num, i, orig) {
        return num + (num != "-" && i && !(i % 3) ? "," : "") + acc;
    }, "") + "." + p[1];
}

そしていくつかのテスト:

formatDollar(45664544.23423) // "$45,664,544.23"
formatDollar(45) // "$45.00"
formatDollar(123) // "$123.00"
formatDollar(7824) // "$7,824.00"
formatDollar(1) // "$1.00"
formatDollar(-1345) // "$-1,345.00
formatDollar(-3) // "$-3.00"
于 2011-03-17T16:28:19.767 に答える
85

現在のすべてのブラウザで動作します

toLocaleString言語に依存した表現で通貨をフォーマットするために使用します ( ISO 4217通貨コードを使用)。

(2500).toLocaleString("en-GB", {style: "currency", currency: "GBP", minimumFractionDigits: 2})

avenmore の南アフリカランドコードスニペットの例:

console.log((2500).toLocaleString("en-ZA", {style: "currency", currency: "ZAR", minimumFractionDigits: 2}))
// -> R 2 500,00
console.log((2500).toLocaleString("en-GB", {style: "currency", currency: "ZAR", minimumFractionDigits: 2}))
// -> ZAR 2,500.00

于 2013-09-25T01:42:45.630 に答える
69

私はあなたが欲しいと思います:

f.nettotal.value = "$" + showValue.toFixed(2);
于 2012-02-16T20:42:09.653 に答える
30

わかりました、あなたが言ったことに基づいて、私はこれを使用しています:

var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1);

var AmountWithCommas = Amount.toLocaleString();
var arParts = String(AmountWithCommas).split(DecimalSeparator);
var intPart = arParts[0];
var decPart = (arParts.length > 1 ? arParts[1] : '');
decPart = (decPart + '00').substr(0,2);

return '£ ' + intPart + DecimalSeparator + decPart;

私は改善の提案を受け入れます (これを行うためだけにYUIを含めたくないです :-) )

「。」を検出する必要があることはすでにわかっています。小数点として使用する代わりに...

于 2008-09-29T15:22:33.140 に答える
29

Numeral.js - @adamwdraper による簡単な数値フォーマットのための JavaScript ライブラリ

numeral(23456.789).format('$0,0.00'); // = "$23,456.79"
于 2012-10-02T21:07:30.157 に答える
27

私はライブラリGlobalize(Microsoftから)を使用しています:

数値、通貨、日付をローカライズし、ユーザーのロケールに応じて正しい方法で自動的にフォーマットするのは素晴らしいプロジェクトです。...そしてそれはjQuery拡張であるはずですが、現在は100%独立したライブラリです。ぜひお試しください!:)

于 2011-07-22T07:47:51.657 に答える
26

javascript-number-formatter (以前は Google Code で)

  • 短く、高速で、柔軟でありながらスタンドアロンです。
  • #,##0.00のように、または否定を使用して、標準の数値書式を受け入れ-000.####ます。
  • # ##0,00#,###.###'###.##または任意の種類の非番号記号などの国の形式を受け入れます。
  • 任意の数字のグループ化を受け入れます。#,##,#0.000または#,###0.##すべて有効です。
  • 冗長/簡単なフォーマットを受け入れます。##,###,##.#または0#,#00#.###0#すべてOKです。
  • 自動数値丸め。
  • シンプルなインターフェースで、次のようにマスクと値を指定するだけです: format( "0.0000", 3.141592).
  • マスクにプレフィックスとサフィックスを含める

(その README からの抜粋)

于 2011-07-16T05:09:18.193 に答える
25

正規表現を使用した短い方法 (スペース、コンマ、またはポイントを挿入するため):

    Number.prototype.toCurrencyString = function(){
        return this.toFixed(2).replace(/(\d)(?=(\d{3})+\b)/g, '$1 ');
    }

    n = 12345678.9;
    alert(n.toCurrencyString());
于 2012-01-04T11:47:09.560 に答える
24

元の方法を提供してくれたJonathan Mに+1 。これは明示的に通貨フォーマッタであるため、先に進んで通貨記号 (デフォルトは「$」) を出力に追加し、デフォルトのコンマを千単位の区切り記号として追加しました。実際に通貨記号 (または千単位の区切り記号) が必要ない場合は、引数として "" (空の文字列) を使用してください。

Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator, currencySymbol) {
    // check the args and supply defaults:
    decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
    decSeparator = decSeparator == undefined ? "." : decSeparator;
    thouSeparator = thouSeparator == undefined ? "," : thouSeparator;
    currencySymbol = currencySymbol == undefined ? "$" : currencySymbol;

    var n = this,
        sign = n < 0 ? "-" : "",
        i = parseInt(n = Math.abs(+n || 0).toFixed(decPlaces)) + "",
        j = (j = i.length) > 3 ? j % 3 : 0;

    return sign + currencySymbol + (j ? i.substr(0, j) + thouSeparator : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator) + (decPlaces ? decSeparator + Math.abs(n - i).toFixed(decPlaces).slice(2) : "");
};
于 2012-06-30T01:45:48.080 に答える
23

主要な部分は千区切り記号を挿入することであり、これは次のように実行できます。

<script type="text/javascript">
  function ins1000Sep(val) {
    val = val.split(".");
    val[0] = val[0].split("").reverse().join("");
    val[0] = val[0].replace(/(\d{3})/g, "$1,");
    val[0] = val[0].split("").reverse().join("");
    val[0] = val[0].indexOf(",") == 0 ? val[0].substring(1) : val[0];
    return val.join(".");
  }

  function rem1000Sep(val) {
    return val.replace(/,/g, "");
  }

  function formatNum(val) {
    val = Math.round(val*100)/100;
    val = ("" + val).indexOf(".") > -1 ? val + "00" : val + ".00";
    var dec = val.indexOf(".");
    return dec == val.length-3 || dec == 0 ? val : val.substring(0, dec+3);
  }
</script>

<button onclick="alert(ins1000Sep(formatNum(12313231)));">
于 2008-09-29T15:06:49.417 に答える
22

PHP関数「number_format」のJavaScriptポートがあります。

PHP開発者にとって使いやすく、認識しやすいので、非常に便利だと思います。

function number_format (number, decimals, dec_point, thousands_sep) {
    var n = number, prec = decimals;

    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };

    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;

    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec);
    // Fix for Internet Explorer parseFloat(0.55).toFixed(0) = 0;

    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
               _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}

(オリジナルからのコメントブロック、例とクレジットのために以下に含まれています)

// Formats a number with grouped thousands
//
// version: 906.1806
// discuss at: http://phpjs.org/functions/number_format
// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// +     bugfix by: Michael White (http://getsprink.com)
// +     bugfix by: Benjamin Lupton
// +     bugfix by: Allan Jensen (http://www.winternet.no)
// +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// +     bugfix by: Howard Yeend
// +    revised by: Luke Smith (http://lucassmith.name)
// +     bugfix by: Diogo Resende
// +     bugfix by: Rival
// +     input by: Kheang Hok Chin (http://www.distantia.ca/)
// +     improved by: davook
// +     improved by: Brett Zamir (http://brett-zamir.me)
// +     input by: Jay Klehr
// +     improved by: Brett Zamir (http://brett-zamir.me)
// +     input by: Amir Habibi (http://www.residence-mixte.com/)
// +     bugfix by: Brett Zamir (http://brett-zamir.me)
// *     example 1: number_format(1234.56);
// *     returns 1: '1,235'
// *     example 2: number_format(1234.56, 2, ',', ' ');
// *     returns 2: '1 234,56'
// *     example 3: number_format(1234.5678, 2, '.', '');
// *     returns 3: '1234.57'
// *     example 4: number_format(67, 2, ',', '.');
// *     returns 4: '67,00'
// *     example 5: number_format(1000);
// *     returns 5: '1,000'
// *     example 6: number_format(67.311, 2);
// *     returns 6: '67.31'
// *     example 7: number_format(1000.55, 1);
// *     returns 7: '1,000.6'
// *     example 8: number_format(67000, 5, ',', '.');
// *     returns 8: '67.000,00000'
// *     example 9: number_format(0.9, 0);
// *     returns 9: '1'
// *     example 10: number_format('1.20', 2);
// *     returns 10: '1.20'
// *     example 11: number_format('1.20', 4);
// *     returns 11: '1.2000'
// *     example 12: number_format('1.2000', 3);
// *     returns 12: '1.200'
于 2009-08-24T15:30:43.180 に答える
20

Patrick Desjardinsの答えは良さそうに見えますが、私は JavaScript コードをシンプルにすることを好みます。これは、数値を受け取り、それを通貨形式 (ドル記号を除く) で返すために作成したばかりの関数です。

// Format numbers to two decimals with commas
function formatDollar(num) {
    var p = num.toFixed(2).split(".");
    var chars = p[0].split("").reverse();
    var newstr = '';
    var count = 0;
    for (x in chars) {
        count++;
        if(count%3 == 1 && count != 1) {
            newstr = chars[x] + ',' + newstr;
        } else {
            newstr = chars[x] + newstr;
        }
    }
    return newstr + "." + p[1];
}
于 2012-04-16T04:00:55.590 に答える
19

JavaScriptには組み込み関数toFixedがあります。

var num = new Number(349);
document.write("$" + num.toFixed(2));
于 2012-02-17T12:09:46.617 に答える
16
function CurrencyFormatted(amount)
{
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}

ウィルマスターより。

于 2008-09-29T15:16:57.207 に答える
15

GoogleVisualizationAPIのNumberFormatクラスをお勧めします

あなたはこのようなことをすることができます:

var formatter = new google.visualization.NumberFormat({
    prefix: '$',
    pattern: '#,###,###.##'
});

formatter.formatValue(1000000); // $ 1,000,000
于 2012-10-02T21:15:27.087 に答える
15

ネイティブの JavaScript Inlt を使用するだけです

オプションを使用してその値をフォーマットするだけです

const number = 1233445.5678
console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number));

mozilla ドキュメント リンク

于 2021-07-26T21:35:42.260 に答える
14

これは少し遅れるかもしれませんが、これは私が同僚のために作成した方法で、.toCurrencyString()すべての数値にロケール対応関数を追加します。内部化は、通貨記号ではなく、数値のグループ化のみを目的としています。ドルを出力する場合は"$"、供給されたとおりに使用してください。$123 4567日本または中国では、米国と同じ米ドルの数値であるため$1,234,567です。ユーロなどを出力する場合は、通貨記号をから変更し"$"ます。

HTML <head>セクションの任意の場所、または必要に応じて、使用する直前にこれを宣言します。

  Number.prototype.toCurrencyString = function(prefix, suffix) {
    if (typeof prefix === 'undefined') { prefix = '$'; }
    if (typeof suffix === 'undefined') { suffix = ''; }
    var _localeBug = new RegExp((1).toLocaleString().replace(/^1/, '').replace(/\./, '\\.') + "$");
    return prefix + (~~this).toLocaleString().replace(_localeBug, '') + (this % 1).toFixed(2).toLocaleString().replace(/^[+-]?0+/,'') + suffix;
  }

これで完了です。(number).toCurrencyString()数値を通貨として出力する必要がある場所で使用します。

var MyNumber = 123456789.125;
alert(MyNumber.toCurrencyString()); // alerts "$123,456,789.13"
MyNumber = -123.567;
alert(MyNumber.toCurrencyString()); // alerts "$-123.57"
于 2013-02-06T17:42:14.607 に答える
14

通常、同じことを行うには複数の方法がありますがNumber.prototype.toLocaleString、ユーザー設定に基づいて異なる値を返す可能性があるため、使用は避けます。

また、拡張することもお勧めしませんNumber.prototype- ネイティブ オブジェクト プロトタイプの拡張は、他の人のコード (ライブラリ/フレームワーク/プラグインなど) と競合する可能性があり、将来の JavaScript 実装/バージョンと互換性がない可能性があるため、悪い習慣です。

正規表現が問題に対する最良のアプローチであると信じています。これが私の実装です。

/**
 * Converts number into currency format
 * @param {number} number    Number that should be converted.
 * @param {string} [decimalSeparator]    Decimal separator, defaults to '.'.
 * @param {string} [thousandsSeparator]    Thousands separator, defaults to ','.
 * @param {int} [nDecimalDigits]    Number of decimal digits, defaults to `2`.
 * @return {string} Formatted string (e.g. numberToCurrency(12345.67) returns '12,345.67')
 */
function numberToCurrency(number, decimalSeparator, thousandsSeparator, nDecimalDigits){
    //default values
    decimalSeparator = decimalSeparator || '.';
    thousandsSeparator = thousandsSeparator || ',';
    nDecimalDigits = nDecimalDigits == null? 2 : nDecimalDigits;

    var fixed = number.toFixed(nDecimalDigits), //limit/add decimal digits
        parts = new RegExp('^(-?\\d{1,3})((?:\\d{3})+)(\\.(\\d{'+ nDecimalDigits +'}))?$').exec( fixed ); //separate begin [$1], middle [$2] and decimal digits [$4]

    if(parts){ //number >= 1000 || number <= -1000
        return parts[1] + parts[2].replace(/\d{3}/g, thousandsSeparator + '$&') + (parts[4] ? decimalSeparator + parts[4] : '');
    }else{
        return fixed.replace('.', decimalSeparator);
    }
}
于 2010-07-19T19:26:07.880 に答える
9

Patrick Desjardins (元 Daok) の例は、私にとってはうまくいきました。誰かが興味を持っている場合は、CoffeeScript に移植しました。

Number.prototype.toMoney = (decimals = 2, decimal_separator = ".", thousands_separator = ",") ->
    n = this
    c = if isNaN(decimals) then 2 else Math.abs decimals
    sign = if n < 0 then "-" else ""
    i = parseInt(n = Math.abs(n).toFixed(c)) + ''
    j = if (j = i.length) > 3 then j % 3 else 0
    x = if j then i.substr(0, j) + thousands_separator else ''
    y = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_separator)
    z = if c then decimal_separator + Math.abs(n - i).toFixed(c).slice(2) else ''
    sign + x + y + z
于 2011-04-15T19:03:57.517 に答える
9

YUIコードベースは、次のフォーマットを使用します。

format: function(nData, oConfig) {
    oConfig = oConfig || {};

    if(!YAHOO.lang.isNumber(nData)) {
        nData *= 1;
    }

    if(YAHOO.lang.isNumber(nData)) {
        var sOutput = nData + "";
        var sDecimalSeparator = (oConfig.decimalSeparator) ? oConfig.decimalSeparator : ".";
        var nDotIndex;

        // Manage decimals
        if(YAHOO.lang.isNumber(oConfig.decimalPlaces)) {
            // Round to the correct decimal place
            var nDecimalPlaces = oConfig.decimalPlaces;
            var nDecimal = Math.pow(10, nDecimalPlaces);
            sOutput = Math.round(nData*nDecimal)/nDecimal + "";
            nDotIndex = sOutput.lastIndexOf(".");

            if(nDecimalPlaces > 0) {
                // Add the decimal separator
                if(nDotIndex < 0) {
                    sOutput += sDecimalSeparator;
                    nDotIndex = sOutput.length-1;
                }
                // Replace the "."
                else if(sDecimalSeparator !== "."){
                    sOutput = sOutput.replace(".",sDecimalSeparator);
                }
                // Add missing zeros
                while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) {
                    sOutput += "0";
                }
            }
        }

        // Add the thousands separator
        if(oConfig.thousandsSeparator) {
            var sThousandsSeparator = oConfig.thousandsSeparator;
            nDotIndex = sOutput.lastIndexOf(sDecimalSeparator);
            nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length;
            var sNewOutput = sOutput.substring(nDotIndex);
            var nCount = -1;
            for (var i=nDotIndex; i>0; i--) {
                nCount++;
                if ((nCount%3 === 0) && (i !== nDotIndex)) {
                    sNewOutput = sThousandsSeparator + sNewOutput;
                }
                sNewOutput = sOutput.charAt(i-1) + sNewOutput;
            }
            sOutput = sNewOutput;
        }

        // Prepend prefix
        sOutput = (oConfig.prefix) ? oConfig.prefix + sOutput : sOutput;

        // Append suffix
        sOutput = (oConfig.suffix) ? sOutput + oConfig.suffix : sOutput;

        return sOutput;
    }
    // Still not a number. Just return it unaltered
    else {
        return nData;
    }
}

YUI ライブラリは構成可能であるため、oConfig.decimalSeparator を「.」に置き換えるなど、編集が必要です。

于 2008-09-29T15:17:49.500 に答える
8

元の要件を満たす最小限のアプローチ:

function formatMoney(n) {
    return "$ " + (Math.round(n * 100) / 100).toLocaleString();
}

@Daniel Magliola : その通りです。上記は性急で不完全な実装でした。修正された実装は次のとおりです。

function formatMoney(n) {
    return "$ " + n.toLocaleString().split(".")[0] + "."
        + n.toFixed(2).split(".")[1];
}
于 2008-09-29T16:02:44.757 に答える
7

tggagne は正しいです。以下の私の解決策は、浮動小数点の丸めのために良くありません。また、 toLocaleString 関数には一部のブラウザー サポートがありません。してはいけないことをアーカイブする目的で、以下のコメントを残します。:)

Date.prototype.toLocaleString()

(古い解決策)代わりにPatrick Dejardins の解決策を使用してください。

これは、JavaScript バージョン 1.0 以降でサポートされている toLocaleString() を使用する簡潔なソリューションです。この例では、通貨を米ドルに指定していますが、「USD」の代わりに「GBP」を使用してポンドに切り替えることができます。

var formatMoney = function (value) {
    // Convert the value to a floating point number in case it arrives as a string.
    var numeric = parseFloat(value);
    // Specify the local currency.
    return numeric.toLocaleString('USD', { style: 'currency', currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

詳細については 、国際化とローカリゼーション、通貨 を参照してください。

于 2015-05-04T15:09:29.710 に答える
5

Intl.NumberFormat

var number = 3500;
alert(new Intl.NumberFormat().format(number));
// → "3,500" if in US English locale

またはJavaScript の PHP の number_format

于 2014-09-10T01:19:56.420 に答える
5

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

  • 短く、高速で、柔軟でありながらスタンドアロンです。MIT ライセンス情報、空白行、コメントを含めてわずか 75 行です。
  • #,##0.00 または否定 -000.#### のような標準の数値形式を受け入れます。
  • # ##0,00、#、###.##、#####.## などの国の形式、または任意の種類の非番号記号を受け入れます。
  • 任意の数字のグループ化を受け入れます。#,##,#0.000 または #,###0.## はすべて有効です。
  • 冗長/簡単なフォーマットを受け入れます。##,###,##.# または 0#,#00#.###0# はすべて OK です。
  • 自動数値丸め。
  • シンプルなインターフェース。次のようにマスクと値を指定するだけです: format( "0.0000", 3.141592)

更新これは、最も一般的なタスクのための私の自作ppユーティリティです。

var NumUtil = {};

/**
  Petty print 'num' wth exactly 'signif' digits.
  pp(123.45, 2) == "120"
  pp(0.012343, 3) == "0.0123"
  pp(1.2, 3) == "1.20"
*/
NumUtil.pp = function(num, signif) {
    if (typeof(num) !== "number")
        throw 'NumUtil.pp: num is not a number!';
    if (isNaN(num))
        throw 'NumUtil.pp: num is NaN!';
    if (num < 1e-15 || num > 1e15)
        return num;
    var r = Math.log(num)/Math.LN10;
    var dot = Math.floor(r) - (signif-1);
    r = r - Math.floor(r) + (signif-1);
    r = Math.round(Math.exp(r * Math.LN10)).toString();
    if (dot >= 0) {
        for (; dot > 0; dot -= 1)
            r += "0";
        return r;
    } else if (-dot >= r.length) {
        var p = "0.";
        for (; -dot > r.length; dot += 1) {
            p += "0";
        }
        return p+r;
    } else {
        return r.substring(0, r.length + dot) + "." + r.substring(r.length + dot);
    }
}

/** Append leading zeros up to 2 digits. */
NumUtil.align2 = function(v) {
    if (v < 10)
        return "0"+v;
    return ""+v;
}
/** Append leading zeros up to 3 digits. */
NumUtil.align3 = function(v) {
    if (v < 10)
        return "00"+v;
    else if (v < 100)
        return "0"+v;
    return ""+v;
}

NumUtil.integer = {};

/** Round to integer and group by 3 digits. */
NumUtil.integer.pp = function(num) {
    if (typeof(num) !== "number") {
        console.log("%s", new Error().stack);
        throw 'NumUtil.integer.pp: num is not a number!';
    }
    if (isNaN(num))
        throw 'NumUtil.integer.pp: num is NaN!';
    if (num > 1e15)
        return num;
    if (num < 0)
        throw 'Negative num!';
    num = Math.round(num);
    var group = num % 1000;
    var integ = Math.floor(num / 1000);
    if (integ === 0) {
        return group;
    }
    num = NumUtil.align3(group);
    while (true) {
        group = integ % 1000;
        integ = Math.floor(integ / 1000);
        if (integ === 0)
            return group + " " + num;
        num = NumUtil.align3(group) + " " + num;
    }
    return num;
}

NumUtil.currency = {};

/** Round to coins and group by 3 digits. */
NumUtil.currency.pp = function(amount) {
    if (typeof(amount) !== "number")
        throw 'NumUtil.currency.pp: amount is not a number!';
    if (isNaN(amount))
        throw 'NumUtil.currency.pp: amount is NaN!';
    if (amount > 1e15)
        return amount;
    if (amount < 0)
        throw 'Negative amount!';
    if (amount < 1e-2)
        return 0;
    var v = Math.round(amount*100);
    var integ = Math.floor(v / 100);
    var frac = NumUtil.align2(v % 100);
    var group = integ % 1000;
    integ = Math.floor(integ / 1000);
    if (integ === 0) {
        return group + "." + frac;
    }
    amount = NumUtil.align3(group);
    while (true) {
        group = integ % 1000;
        integ = Math.floor(integ / 1000);
        if (integ === 0)
            return group + " " + amount + "." + frac;
        amount = NumUtil.align3(group) + " " + amount;
    }
    return amount;
}
于 2013-01-15T14:07:36.930 に答える
4

Jonathan Mのコードは私には複雑すぎるように見えたので、書き直して、Firefox v30 で約 30%、Chrome v35 で 60% の速度向上を得ました ( http://jsperf.com/number-formating2 ):

Number.prototype.formatNumber = function(decPlaces, thouSeparator, decSeparator) {
    decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
    decSeparator = decSeparator == undefined ? "." : decSeparator;
    thouSeparator = thouSeparator == undefined ? "," : thouSeparator;

    var n = this.toFixed(decPlaces);
    if (decPlaces) {
        var i = n.substr(0, n.length - (decPlaces + 1));
        var j = decSeparator + n.substr(-decPlaces);
    } else {
        i = n;
        j = '';
    }

    function reverse(str) {
        var sr = '';
        for (var l = str.length - 1; l >= 0; l--) {
            sr += str.charAt(l);
        }
        return sr;
    }

    if (parseInt(i)) {
        i = reverse(reverse(i).replace(/(\d{3})(?=\d)/g, "$1" + thouSeparator));
    }
    return i + j;
};

使用法:

var sum = 123456789.5698;
var formatted = '$' + sum.formatNumber(2, ',', '.'); // "$123,456,789.57"
于 2014-06-26T10:26:55.647 に答える
4

数値を通貨形式に変換するための短くて最適なものを次に示します。

function toCurrency(amount){
    return amount.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

// usage: toCurrency(3939920.3030);
于 2014-01-21T10:18:07.740 に答える
4

この回答は次の基準を満たしています。

  • 外部依存関係に依存しません。
  • ローカリゼーションをサポートします。
  • テスト/証明があります。
  • シンプルでベストなコーディング プラクティスを使用します (複雑な正規表現は使用せず、標準のコーディング パターンを使用します)。

このコードは、他の回答の概念に基づいて構築されています。それが懸念される場合、その実行速度はここに投稿されたものよりも優れているはずです.

var decimalCharacter = Number("1.1").toLocaleString().substr(1,1);
var defaultCurrencyMarker = "$";
function formatCurrency(number, currencyMarker) {
    if (typeof number != "number")
        number = parseFloat(number, 10);

    // if NaN is passed in or comes from the parseFloat, set it to 0.
    if (isNaN(number))
        number = 0;

    var sign = number < 0 ? "-" : "";
    number = Math.abs(number);    // so our signage goes before the $ symbol.

    var integral = Math.floor(number);
    var formattedIntegral = integral.toLocaleString();

    // IE returns "##.00" while others return "##"
    formattedIntegral = formattedIntegral.split(decimalCharacter)[0];

    var decimal = Math.round((number - integral) * 100);
    return sign + (currencyMarker || defaultCurrencyMarker) +
        formattedIntegral  +
        decimalCharacter +
        decimal.toString() + (decimal < 10 ? "0" : "");
}

これらのテストは、米国ロケールのマシンでのみ機能します。この決定は単純化のために行われました。これは、不適切な入力 (不適切な自動ローカリゼーション) が発生し、不適切な出力の問題が発生する可能性があるためです。

var tests = [
    // [ input, expected result ]
    [123123, "$123,123.00"],    // no decimal
    [123123.123, "$123,123.12"],    // decimal rounded down
    [123123.126, "$123,123.13"],    // decimal rounded up
    [123123.4, "$123,123.40"],    // single decimal
    ["123123", "$123,123.00"],    // repeat subset of the above using string input.
    ["123123.123", "$123,123.12"],
    ["123123.126", "$123,123.13"],
    [-123, "-$123.00"]    // negatives
];

for (var testIndex=0; testIndex < tests.length; testIndex++) {
    var test = tests[testIndex];
    var formatted = formatCurrency(test[0]);
    if (formatted == test[1]) {
        console.log("Test passed, \"" + test[0] + "\" resulted in \"" + formatted + "\"");
    } else {
        console.error("Test failed. Expected \"" + test[1] + "\", got \"" + formatted + "\"");
    }
}
于 2013-08-15T03:22:51.337 に答える
4

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat 例: ロケールの使用

この例は、ローカライズされた数値形式のバリエーションの一部を示しています。アプリケーションのユーザー インターフェイスで使用される言語の形式を取得するには、locales 引数を使用してその言語 (および場合によってはいくつかのフォールバック言語) を指定してください。

変数番号 = 123456.789;

// ドイツ語ではカンマを小数点として、ピリオドを 1000 単位で使用します console.log(new Intl.NumberFormat('de-DE').format(number)); // → 123.456,789

// ほとんどのアラビア語圏の国では、アラビア語は実際のアラビア数字を使用します console.log(new Intl.NumberFormat('ar-EG').format(number)); // → ١٢٣٤٥٦٫٧٨٩

// インドは千/数十万/千万の区切り文字を使用します console.log(new Intl.NumberFormat('en-IN').format(number));

于 2014-10-22T11:21:08.627 に答える
3

日付と通貨を扱う単純なライブラリを見つけるのに苦労したので、独自のライブラリを作成しました: https://github.com/dericeira/slimFormatter.js

そのような単純な:

var number = slimFormatter.currency(2000.54);
于 2016-11-10T18:32:34.290 に答える
3

JavaScript には「formatNumber」に相当するものはありません。自分で書くか、すでにこれを行っているライブラリを見つけることができます。

于 2012-02-16T20:40:59.920 に答える
3

これは、XMLilley によって提供されたコードからの mootools 1.2 の実装です...

Number.implement('format', function(decPlaces, thouSeparator, decSeparator){
decPlaces = isNaN(decPlaces = Math.abs(decPlaces)) ? 2 : decPlaces;
decSeparator = decSeparator === undefined ? '.' : decSeparator;
thouSeparator = thouSeparator === undefined ? ',' : thouSeparator;

var num = this,
    sign = num < 0 ? '-' : '',
    i = parseInt(num = Math.abs(+num || 0).toFixed(decPlaces)) + '',
    j = (j = i.length) > 3 ? j % 3 : 0;

return sign + (j ? i.substr(0, j) + thouSeparator : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thouSeparator) + (decPlaces ? decSeparator + Math.abs(num - i).toFixed(decPlaces).slice(2) : '');
});
于 2013-01-29T05:21:56.043 に答える
3

正規表現を使ったより速い方法:

Number.prototype.toMonetaryString = function() {
  var n = this.toFixed(2), m;
  //var = this.toFixed(2).replace(/\./, ','); For comma separator
  // with a space for thousands separator
  while ((m = n.replace(/(\d)(\d\d\d)\b/g, '$1 $2')) != n)
      n = m;
  return m;
}

String.prototype.fromMonetaryToNumber = function(s) {
  return this.replace(/[^\d-]+/g, '')/100;
}
于 2011-11-29T15:14:56.363 に答える
3

これはうまくいくかもしれません:

function format_currency(v, number_of_decimals, decimal_separator, currency_sign){
  return (isNaN(v)? v : currency_sign + parseInt(v||0).toLocaleString() + decimal_separator + (v*1).toFixed(number_of_decimals).slice(-number_of_decimals));
}

ループなし、正規表現なし、配列なし、風変わりな条件なし。

于 2011-05-11T19:22:26.790 に答える
3

回答の多くには役立つアイデアが含まれていましたが、どれも私のニーズに合うものではありませんでした。そこで、すべてのアイデアを使用して、この例を作成しました。

function Format_Numb(fmt){
    var decimals = isNaN(decimals) ? 2 : Math.abs(decimals);
    if(typeof decSgn === "undefined") decSgn = ".";
    if(typeof kommaSgn === "undefined") kommaSgn= ",";

    var s3digits = /(\d{1,3}(?=(\d{3})+(?=[.]|$))|(?:[.]\d*))/g;
    var dflt_nk = "00000000".substring(0, decimals);

    //--------------------------------
    // handler for pattern: "%m"
    var _f_money = function(v_in){
                       var v = v_in.toFixed(decimals);
                       var add_nk = ",00";
                       var arr = v.split(".");
                       return arr[0].toString().replace(s3digits, function ($0) {
                           return ($0.charAt(0) == ".")
                                   ? ((add_nk = ""), (kommaSgn + $0.substring(1)))
                                   : ($0 + decSgn);
                           })
                           + ((decimals > 0)
                                 ? (kommaSgn
                                       + (
                                           (arr.length > 1)
                                           ? arr[1]
                                           : dflt_nk
                                       )
                                   )
                                 : ""
                           );
                   }

    // handler for pattern: "%<len>[.<prec>]f"
    var _f_flt = function(v_in, l, prec){
        var v = (typeof prec !== "undefined") ? v_in.toFixed(prec) : v_in;
        return ((typeof l !== "undefined") && ((l=l-v.length) > 0))
                ? (Array(l+1).join(" ") + v)
                : v;
    }

    // handler for pattern: "%<len>x"
    var _f_hex = function(v_in, l, flUpper){
        var v = Math.round(v_in).toString(16);
        if(flUpper) v = v.toUpperCase();
        return ((typeof l !== "undefined") && ((l=l-v.length) > 0))
                ? (Array(l+1).join("0") + v)
                : v;
    }

    //...can be extended..., just add the function, for example:    var _f_octal = function( v_in,...){
    //--------------------------------

    if(typeof(fmt) !== "undefined"){
        //...can be extended..., just add the char, for example "O":    MFX -> MFXO
        var rpatt = /(?:%([^%"MFX]*)([MFX]))|(?:"([^"]*)")|("|%%)/gi;
        var _qu = "\"";
        var _mask_qu = "\\\"";
        var str = fmt.toString().replace(rpatt, function($0, $1, $2, $3, $4){
                      var f;
                      if(typeof $1 !== "undefined"){
                          switch($2.toUpperCase()){
                              case "M": f = "_f_money(v)";    break;

                              case "F": var n_dig0, n_dig1;
                                        var re_flt =/^(?:(\d))*(?:[.](\d))*$/;
                                        $1.replace(re_flt, function($0, $1, $2){
                                            n_dig0 = $1;
                                            n_dig1 = $2;
                                        });
                                        f = "_f_flt(v, " + n_dig0 + "," + n_dig1 + ")";    break;

                              case "X": var n_dig = "undefined";
                                        var re_flt = /^(\d*)$/;
                                        $1.replace(re_flt, function($0){
                                            if($0 != "") n_dig = $0;
                                        });
                                        f = "_f_hex(v, " + n_dig + "," + ($2=="X") + ")";    break;
                              //...can be extended..., for example:    case "O":
                          }
                          return "\"+"+f+"+\"";
                      } else if(typeof $3 !== "undefined"){
                          return _mask_qu + $3 + _mask_qu;
                      } else {
                          return ($4 == _qu) ? _mask_qu : $4.charAt(0);
                      }
                  });

        var cmd =     "return function(v){"
                +     "if(typeof v === \"undefined\")return \"\";"  // null returned as empty string
                +     "if(!v.toFixed) return v.toString();"         // not numb returned as string
                +     "return \"" + str + "\";"
                + "}";

        //...can be extended..., just add the function name in the 2 places:
        return new Function("_f_money,_f_flt,_f_hex", cmd)(_f_money,_f_flt,_f_hex);
    }
}

まず、柔軟性が高く、非常に使いやすいC スタイルのformat-string-definition が必要でした。次のように定義しました。パターン:

%[<len>][.<prec>]f   float, example "%f", "%8.2d", "%.3f"
%m                   money
%[<len>]x            hexadecimal lower case, example "%x", "%8x"
%[<len>]X            hexadecimal upper case, example "%X", "%8X"

私にとってはユーロにする以外にフォーマットする必要がないので、「%m」だけを実装しました。

しかし、これを拡張するのは簡単です... C と同様に、フォーマット文字列はパターンを含む文字列です。たとえば、ユーロの場合: "%m €" ("8.129,33 €" のような文字列を返します)

柔軟性に加えて、テーブルを処理するための非常に高速なソリューションが必要でした。つまり、何千ものセルを処理する場合、書式文字列の処理を複数回実行してはなりません。「format( value, fmt)」のような呼び出しは受け入れられませんが、これは 2 つのステップに分割する必要があります。

// var formatter = Format_Numb( "%m €&quot;);
// simple example for Euro...

//   but we use a complex example:

var formatter = Format_Numb("a%%%3mxx \"zz\"%8.2f°\"  >0x%8X<");

// formatter is now a function, which can be used more than once (this is an example, that can be tested:)

var v1 = formatter(1897654.8198344);

var v2 = formatter(4.2);

... (and thousands of rows)

また、パフォーマンスのために、_f_money は正規表現を囲みます。

第 3 に、次の理由により、「format( value, fmt)」のような呼び出しは受け入れられません。

オブジェクトのさまざまなコレクション (列のセルなど) をさまざまなマスクでフォーマットできるはずですが、処理の時点でフォーマット文字列を処理するものは必要ありません。この時点で、次のような書式設定のみを使用したい

for( var cell in cells){ do_something( cell.col.formatter( cell.value)); }

どのような形式 - .ini ファイル、各列の XML、または他の場所で定義されている可能性がありますが、形式の分析と設定、または国際化の処理はまったく別の場所で処理され、そこでフォーマッタを割り当てたいパフォーマンスの問題を考えずにコレクション:

col.formatter = Format_Numb( _getFormatForColumn(...) );

第 4 に、「寛容な」ソリューションが必要だったので、たとえば、数値の代わりに文字列を渡すと、単純に文字列が返されますが、「null」は空の文字列が返されます。

(また、値が大きすぎる場合、「%4.2f」をフォーマットしても何かが切り取られてはなりません。)

最後に、重要なことですが、パフォーマンスに影響を与えることなく読みやすく、簡単に拡張できる必要があります...たとえば、「8進数値」が必要な場合は、「...拡張可能...」の行を参照してください。 」 - それはとても簡単な作業だと思います。

私の全体的な焦点はパフォーマンスにありました。各「処理ルーチン」 (たとえば、_f_money) をカプセル化して最適化するか、このスレッドまたは他のスレッドで他のアイデアと交換することができます。「準備ルーチン」 (フォーマット文字列の分析と関数の作成) を変更する必要はありません。一度だけ処理する必要があります。その意味では、数千の数値の変換呼び出しのようにパフォーマンスがそれほど重要ではありません。

数字の方法を好むすべての人のために:

Number.prototype.format_euro = (function(formatter){
    return function(){ return formatter(this); }})
(Format_Numb( "%m €&quot;));

var v_euro = (8192.3282).format_euro(); // results: 8.192,33 €

Number.prototype.format_hex = (function(formatter){
    return function(){ return formatter(this); }})
(Format_Numb( "%4x"));

var v_hex = (4.3282).format_hex();

いくつかテストしましたが、コードに多くのバグがある可能性があります。したがって、これは既製のモジュールではなく、私のような非 JavaScript の専門家にとってのアイデアと出発点にすぎません。

このコードには、多くのスタック オーバーフローの投稿からの多くの、そしてほとんど変更されていないアイデアが含まれています。申し訳ありませんが、すべてを参照することはできませんが、すべての専門家に感謝します。

于 2015-02-20T23:40:03.383 に答える
3

これは、VisioN からの回答に大きく基づいています。

function format (val) {
  val = (+val).toLocaleString();
  val = (+val).toFixed(2);
  val += "";
  return val.replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1" + format.thousands);
}

(function (isUS) {
  format.decimal =   isUS ? "." : ",";
  format.thousands = isUS ? "," : ".";
}(("" + (+(0.00).toLocaleString()).toFixed(2)).indexOf(".") > 0));

入力でテストしました:

[   ""
  , "1"
  , "12"
  , "123"
  , "1234"
  , "12345"
  , "123456"
  , "1234567"
  , "12345678"
  , "123456789"
  , "1234567890"
  , ".12"
  , "1.12"
  , "12.12"
  , "123.12"
  , "1234.12"
  , "12345.12"
  , "123456.12"
  , "1234567.12"
  , "12345678.12"
  , "123456789.12"
  , "1234567890.12"
  , "1234567890.123"
  , "1234567890.125"
].forEach(function (item) {
  console.log(format(item));
});

そして、これらの結果を得ました:

0.00
1.00
12.00
123.00
1,234.00
12,345.00
123,456.00
1,234,567.00
12,345,678.00
123,456,789.00
1,234,567,890.00
0.12
1.12
12.12
123.12
1,234.12
12,345.12
123,456.12
1,234,567.12
12,345,678.12
123,456,789.12
1,234,567,890.12
1,234,567,890.12
1,234,567,890.13

楽しみのためだけに。

于 2013-03-21T03:11:21.410 に答える
2

私はこれに貢献したい:

function toMoney(amount) {
    neg = amount.charAt(0);
    amount = amount.replace(/\D/g, '');
    amount = amount.replace(/\./g, '');
    amount = amount.replace(/\-/g, '');

    var numAmount = new Number(amount);
    amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) {
        return i > 0 && c !== "," && (a.length - i) % 3 === 0 ? "." + c : c;
    });

    if(neg == '-')
        return neg + amount;
    else
        return amount;
}

これにより、数値のみを入力することになっているテキスト ボックスで数値を変換できます (このシナリオを考えてみてください)。

これは、数字と文字または任意の文字を含む文字列を貼り付けたとしても、数字のみが存在するはずのテキストボックスを消去します

<html>
<head>
    <script language=="Javascript">
        function isNumber(evt) {
            var theEvent = evt || window.event;
            var key = theEvent.keyCode || theEvent.which;
            key = String.fromCharCode(key);
            if (key.length == 0)
                return;
            var regex = /^[0-9\-\b]+$/;
            if (!regex.test(key)) {
                theEvent.returnValue = false;
                if (theEvent.preventDefault)
                    theEvent.preventDefault();
            }
        }

        function toMoney(amount) {
            neg = amount.charAt(0);
            amount = amount.replace(/\D/g, '');
            amount = amount.replace(/\./g, '');
            amount = amount.replace(/\-/g, '');

            var numAmount = new Number(amount);
            amount = numAmount.toFixed(0).replace(/./g, function(c, i, a) {
                return i > 0 && c !== "," && (a.length - i) % 3 === 0 ? "." + c : c;
            });

            if(neg == '-')
                return neg + amount;
            else
                return amount;
        }

        function clearText(inTxt, newTxt, outTxt) {
            inTxt = inTxt.trim();
            newTxt = newTxt.trim();
            if(inTxt == '' || inTxt == newTxt)
                return outTxt;

            return inTxt;
        }

        function fillText(inTxt, outTxt) {
            inTxt = inTxt.trim();
            if(inTxt != '')
                outTxt = inTxt;

            return outTxt;
        }
    </script>
</head>

<body>
    $ <input name=reca2 id=reca2 type=text value="0" onFocus="this.value = clearText(this.value, '0', '');" onblur="this.value = fillText(this.value, '0'); this.value = toMoney(this.value);" onKeyPress="isNumber(event);" style="width:80px;" />
</body>

</html>
于 2016-01-08T21:53:27.837 に答える
2
String.prototype.toPrice = function () {
    var v;
    if (/^\d+(,\d+)$/.test(this))
        v = this.replace(/,/, '.');
    else if (/^\d+((,\d{3})*(\.\d+)?)?$/.test(this))
        v = this.replace(/,/g, "");
    else if (/^\d+((.\d{3})*(,\d+)?)?$/.test(this))
        v = this.replace(/\./g, "").replace(/,/, ".");
    var x = parseFloat(v).toFixed(2).toString().split("."),
    x1 = x[0],
    x2 = ((x.length == 2) ? "." + x[1] : ".00"),
    exp = /^([0-9]+)(\d{3})/;
    while (exp.test(x1))
        x1 = x1.replace(exp, "$1" + "," + "$2");
    return x1 + x2;
}

alert("123123".toPrice()); //123,123.00
alert("123123,316".toPrice()); //123,123.32
alert("12,312,313.33213".toPrice()); //12,312,313.33
alert("123.312.321,32132".toPrice()); //123,312,321.32
于 2012-06-29T15:17:36.293 に答える
2

パトリックの人気のある答えのCoffeeScript :

Number::formatMoney = (decimalPlaces, decimalChar, thousandsChar) ->
  n = this
  c = decimalPlaces
  d = decimalChar
  t = thousandsChar
  c = (if isNaN(c = Math.abs(c)) then 2 else c)
  d = (if d is undefined then "." else d)
  t = (if t is undefined then "," else t)
  s = (if n < 0 then "-" else "")
  i = parseInt(n = Math.abs(+n or 0).toFixed(c)) + ""
  j = (if (j = i.length) > 3 then j % 3 else 0)
  s + (if j then i.substr(0, j) + t else "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (if c then d + Math.abs(n - i).toFixed(c).slice(2) else "")
于 2012-07-04T20:25:55.643 に答える
2

すでに良い答えがあります。これは楽しみのための簡単な試みです:

function currencyFormat(no) {
  var ar = (+no).toFixed(2).split('.');
  return [
      numberFormat(ar[0] | 0),
      '.',
      ar[1]
  ].join('');
}


function numberFormat(no) {
  var str = no + '';
  var ar = [];
  var i  = str.length -1;

  while(i >= 0) {
    ar.push((str[i-2] || '') + (str[i-1] || '') + (str[i] || ''));
    i = i-3;
  }
  return ar.reverse().join(',');
}

次に、いくつかの例を実行します。

console.log(
  currencyFormat(1),
  currencyFormat(1200),
  currencyFormat(123),
  currencyFormat(9870000),
  currencyFormat(12345),
  currencyFormat(123456.232)
)
于 2015-04-06T13:03:46.940 に答える
2
function getMoney(A){
    var a = new Number(A);
    var b = a.toFixed(2); // Get 12345678.90
    a = parseInt(a); // Get 12345678
    b = (b-a).toPrecision(2); // Get 0.90
    b = parseFloat(b).toFixed(2); // In case we get 0.0, we pad it out to 0.00
    a = a.toLocaleString(); // Put in commas - Internet Explorer also puts in .00, so we'll get 12,345,678.00
    // If Internet Explorer (our number ends in .00)
    if(a < 1 && a.lastIndexOf('.00') == (a.length - 3))
    {
        a = a.substr(0, a.length-3); // Delete the .00
    }
    return a + b.substr(1); // Remove the 0 from b, then return a + b = 12,345,678.90
}
alert(getMoney(12345678.9));

これは Firefox と Internet Explorer で機能します。

于 2010-05-27T09:38:29.470 に答える
1

これが私の...

function thousandCommas(num) {
  num = num.toString().split('.');
  var ints = num[0].split('').reverse();
  for (var out=[],len=ints.length,i=0; i < len; i++) {
    if (i > 0 && (i % 3) === 0) out.push(',');
    out.push(ints[i]);
  }
  out = out.reverse() && out.join('');
  if (num.length === 2) out += '.' + num[1];
  return out;
}
于 2012-10-19T03:43:41.327 に答える
1

シンプルなのが好きです:

function formatPriceUSD(price) {
    var strPrice = price.toFixed(2).toString();
    var a = strPrice.split('');

    if (price > 1000000000)
        a.splice(a.length - 12, 0, ',');

    if (price > 1000000)
        a.splice(a.length - 9, 0, ',');

    if (price > 1000)
        a.splice(a.length - 6, 0, ',');

    return '$' + a.join("");
}
于 2014-09-09T21:28:05.167 に答える
1
于 2019-08-30T11:39:20.153 に答える
0

1 つのコマンドで数値または文字列を通貨文字列に変換するNumberToCurrency.jsを使用するだけです。

于 2021-11-22T23:01:37.643 に答える
0

CurrencyRate.today によるゼロ依存の小さな JavaScript ライブラリ (1kB バイト) は、単純な方法と高度な数値、お金、通貨の書式設定を提供し、すべての書式設定/クラフトを削除し、生の float 値を返します。

https://github.com/dejurin/format-money-js

npm install format-money-js

特徴:

  • from : お金と通貨のフォーマット;

  • un : すべての書式設定/クラフトを削除し、生の float 値を返します。

例 1

const { FormatMoney } = require('format-money-js');

const fm = new FormatMoney({
  decimals: 2
});

console.log(fm.from(12345.67, { symbol: '$' })); // return string: $12,345.67
console.log(fm.un('€12,345;67')); // return number: 12345.67

例 2

const { FormatMoney } = require('format-money-js');

const fm = new FormatMoney({
  decimals: 2
});

console.log(fm.from(
  12345.67, 
  { symbol: '$' },
  true // Parse, return object
  )
);
/* return object: 
{
  source: 12345.67,
  negative: false,
  fullAmount: '12,345.67',
  amount: '12,345',
  decimals: '.67',
  symbol: '$'
}*/
于 2021-07-14T20:36:10.627 に答える
-1

regexp と replace を使用した簡単な方法を次に示します。

function formatCurrency(number, dp, ts) {
  var num = parseFloat(number); // Convert to float
  var pw; // For Internet Explorer
  dp = parseInt(dp, 10); // Decimal point
  dp = isNaN(dp) ? 2 : dp; // Default 2 decimal point
  ts = ts || ','; // Thousands separator

  return num != number ?
    false : // Return false for NaN
    ((0.9).toFixed(0) == '1' ? // For cater Internet Explorer toFixed bug
        num.toFixed(dp) : // Format to fix n decimal point with round up
        (Math.round(num * (pw = Math.pow(10, dp) || 1)) / pw).toFixed(dp) // For fixing Internet Explorer toFixed bug on round up value like 0.9 in toFixed
    ).replace(/^(-?\d{1,3})((\d{3})*)(\.\d+)?$/, function(all, first, subsequence, dmp, dec) { // Separate string into different parts
      return (first || '') + subsequence.replace(/(\d{3})/g, ts + '$1') + (dec || ''); // Add thousands separator and rejoin all parts
    } );
}
于 2011-07-22T07:41:53.127 に答える