LoginSignup
46
48

More than 5 years have passed since last update.

数値文字列に3桁区切りでカンマを入れる処理

Last updated at Posted at 2012-12-26

簡易コード

delimiter.js
var num = '10000000';
num = num.split(/(?=(?:\d{3})+$)/).join();

正規表現は素晴らしい。

(2014/11/07追記)

元々、この実装は「正規表現を使っていかに短く書けるか」「String.prototype.replace のコールバック関数を使わずに書けるか」の着想を元にコーディングしています。
その為、かなり割り切った仕様にしており、下記制約があります。

  • 数値文字列と数値以外の文字列が混在した文字列をサポートしない(完全な数値文字列でなければならない)
  • 整数値のみをサポートし、小数値をサポートしない

本格的なコード

前述でサポートされなかった仕様に対応するためには String.prototype.replace のコールバック関数を利用するしか手段はないと考えています。
具体的には下記のようになります。

insert-comma-delimiter.js
/**
 * insert-comma-delimiter.js
 * Insert commas in a numeric string.
 *
 * @version 1.0.1
 * @author think49
 * @url https://gist.github.com/think49/c13758815bc0af4b19e3
 * @license http://www.opensource.org/licenses/mit-license.php (The MIT License)
 */

'use strict';

/**
 * insert comma delimiter
 * @function
 * @param  {String} numberString Numeric string of decimal or integer.
 * @return {String} Numeric string of comma-separated.
 */
function insertCommaDelimiter (numberString) {
  return numberString.replace(/(\d+)(\.\d+)?/, function (subString, capture1, capture2) {
    capture1 = capture1.split(/(?=(?:\d{3})+$)/).join();
    return capture2 ? capture1 + capture2.replace(/(\d{3})(?=\d)/, '$1,') : capture1;
  });
}


/**
 * test
 */
var strings = ['私の戦闘力は530000です。',
               'STEINS;GATE(シュタインズゲート)世界線の世界線変動率は1.048596です。',
               'Aさんの犯罪係数オーバー10000、執行対象です。対象の脅威判定が更新されました。執行モード、リーサル・エリミネーター。慎重に照準を定め対象を排除してください。'];

console.log(insertCommaDelimiter(strings[0])); // 私の戦闘力は530,000です。
console.log(insertCommaDelimiter(strings[1])); // STEINS;GATE(シュタインズゲート)世界線の世界線変動率は1.048,596です。
console.log(insertCommaDelimiter(strings[2])); // Aさんの犯罪係数オーバー10,000、執行対象です。対象の脅威判定が更新されました。執行モード、リーサル・エリミネーター。慎重に照準を定め対象を排除してください。

参考

46
48
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
46
48