Archive for 12 月 5th, 2008

PHPのnumber_format関数をjavascriptで実装する

Posted in IT on 12 月 5th, 2008 by ishikawa – Be the first to comment

以下のPHPのソースをjavascriptで 実行したい場合は、どのように 記述すれば宜しいでしょうか? – 人力検索はてな を読んで。

要するにPHPのnumber_format関数をjavascriptで作って欲しいという話。javascriptで使いたいシーンというのを余り思いつかないのだけど、実装するのは別に難しくは無い。

一応PHPのnumber_formatを説明しておくと、例えば number_format(12000, 2) をすると、12,000.00 が返ってくる。位取りのカンマと数値の丸めを行う関数。詳しくはPHP: number_format – Manualを見てください。

これをNumberオブジェクトのメソッドとして number_format と同様に汎用性を持たせた物を追加して、フォーマットされた文字列を返すようにすれば、使いやすいはず。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Number.prototype.format = function(dec, c, p) {
  if (typeof(dec) == 'undefined') { dec = 0; }
  if (typeof(c) == 'undefined') { c = ','; }
  if (typeof(p) == 'undefined') { p = '.'; }
 
  var place = Math.pow(10, dec);
  var num = Math.round(this * place) / place;
  var values = num.toString().split('.');
  if (values.length == 1) { values.push(''); }
 
  while (values[0] != (values[0] = values[0].replace(/^(-?\d+)(\d{3})/, '$1' + c + '$2')));
  while (dec != values[1].length) { values[1] += '0'; }
  return values.join(p);
}

これを使うと以下の様になる。(引数の取り順が number_formatとは異なります)

1
2
3
4
5
6
Number("+01344247.000570").format(1, ' ', ',');// 1 344 247,0 (フランス記法対応)
Number("-01344247.000570").format(2);// -1,344,247.00
Number("+01344247.000570").format(3);// 1,344,247.001
Number("+01344247.000570").format(4);// 1,344,247.0006
Number("+01344247.000570").format(5);// 1,344,247.00057
Number("+01344247.000570").format(6);// 1,344,247.000570

この Number#format を使ってはてなの人力検索の質問を実装すると以下の様になる。

1
2
3
4
5
6
function changePrice(bbb) {
    aaa = bbb.replace(/,/g, '');
    aaa = Number(aaa/10000).format(2);
    return aaa;
}
changePrice("32546447");// 3,254.64

使うシーンが思い浮かばないとは言ったけど、表示した数値が変化する状況は良くあるので、ある程度大きな数値を扱うなら使う事もあるかもなぁ。