Formatting/Parsing Numbers in jQuery
Javascript製のNumber Formatter。
テキストフィールドなどに設定した数値をフォーマットする。
http://code.google.com/p/jquery-numberformatter/
最小のサンプル。
<html> <head> <script src="jquery-1.3.2.js" type="text/javascript"></script> <script src="jquery.numberformatter-1.1.2.js" type="text/javascript"></script> <script type="text/javascript"> <!-- // $(document).ready(function() { $('#disptext').format({format:'#,###.##', locale:'jp'}); }); // --> </script> </head> <body> <span id=disptext>4335.20909090</span> </body> </html>
整形のフォーマットが「#,###.##」なので、
「4335.20909090」が、「4,335.21」と整形されて表示されます。
フォーマットのオプションは、
formatキーで整形ルール、
localeキーでロケール、
decimalSeparatorAlwaysShownで、最後の小数点を削除するかしないか、(3.0に、フォーマット###.#と指定した時など)
を指定しますが、
$('#disptext').format({format:'#,###.##', locale:'jp', decimalSeparatorAlwaysShown:false});
デフォルト値が設定されているので、オプション無しでも動作します。
$('#disptext').format({});
しかし、日本語環境で使うなら、format、localeくらいは指定して、次のように使うのが良いでしょう。
デフォルトオプションでは、小数点下2桁まで表示してしまいます。
$('#disptext').format({format:'#,###.##', locale:'jp'});
最後に、当たり前ですけど使うときは、例の中の、
$('#disptext')
のところは、適切なものに変更してください。
テキストフィールドでも、spanに囲まれた領域でも、このフォーマッタで整形できます。