パスワードを忘れた? アカウント作成
452905 journal

dsegの日記: 数字にコンマを挟み込む 1

日記 by dseg
", "image": "https://srad.jp/static/topics/" }
"ありがち"な、金額をあらわす数列に、1000単位でカンマを挟み込む処理。
とりあえずJavaScriptとPHP用に書いてみた。

<script language="javascript">
function commish(s) {
  while(/\d\d\d\d/.test(s)) // 'lookahead' requires javascript 1.5
    s = s.replace(/(\d)(\d\d\d)(?!\d)/g, "$1,$2");
  return s;
}
</script>

<?php
function commish($s, $delim = ',') {
  while(preg_match('/\d\d\d\d/', $s))
    $s = preg_replace('/(\d)(\d\d\d)(?!\d)/', '\\1$delim\\2', $s);
  return $s;
}
?>

追記:
php にはnumber_formatなる関数があるそうな。
あら~...
http://www.php.net/number_format
この議論は賞味期限が切れたので、アーカイブ化されています。 新たにコメントを付けることはできません。
typodupeerror

一つのことを行い、またそれをうまくやるプログラムを書け -- Malcolm Douglas McIlroy

読み込み中...