LoginSignup
5
3

More than 1 year has passed since last update.

サイズをKBやMB、数を万や億などに変換する

Last updated at Posted at 2017-05-31

自分用メモ
「1024B => 1KB」「1000000000 => 10億」みたいに丸めてくれるやつ作ってみた。
希に欲しい時があるので残しておく。サッと作っただけなので、バグとかあるかも。
こういうのって、世にいくらでもあるだろうに、見つけられない情弱な自分が悲しい。

NumberFormat.js
/**
 * 小数点指定できる四捨五入
 * @see: http://qiita.com/chiyoyo/items/eac6d7cb4d3d6a6ab3fb
 */
Math.round = function (round_original) {
  return function (number, pricision) {
    var _pow;
    switch (arguments.length) {
    case 1:
      return round_original(number);
    case 2:
      _pow = Math.pow(10, pricision);
      return round_original(number * _pow) / _pow;
    }
  }
}(Math.round);

/**
 * 数値フォーマット
 */
var NumberFormat = {
    /**
     * 任意の数に丸めた数値文字を取得する
     * 閾値にはマイナスの値は指定できません
     * ex.) 1024 => 1KB, 120000000 => 1.2億
     *
     * @param float size 元の数値
     * @param array unit 単位設定 [{threshold: 閾値, unit:'単位名'}]
     * @param int dec 小数点以下の数
     * @param boolean separate 桁区切りの有無
     * @return string
     */
    custom_format : function(size, units, dec, separate) {
        // 降順ソート
        units.sort(function (a, b) {
            if (a.threshold < b.threshold) return 1;
            if (a.threshold > b.threshold) return -1;
            return 0;
        });

        unit = {};
        for (i = 0 ; i < units.length ; i++) {
            unit = units[i];
            if (Math.abs(unit.threshold <= Math.abs(size))) {
                break;
            }
        }

        // 0除算を回避
        if (unit.threshold == 0) unit.threshold = 1;

        after_size = Math.round(size / unit.threshold, dec);

        result = '';
        if (separate) {
            result = after_size.toLocaleString();
        }

        return result + unit.unit;
    },

    // バイト丸めフォーマット
    byte_format : function(size, dec, separate) {
        units = [
            {unit: 'B',  threshold: 0},
            {unit: 'KB', threshold: 1024},
            {unit: 'MB',  threshold: 1024 ** 2},
            {unit: 'GB',  threshold: 1024 ** 3},
            {unit: 'TB',  threshold: 1024 ** 4},
            {unit: 'PB',  threshold: 1024 ** 5}
        ];
        return this.custom_format(size, units, dec, separate);
    },

    // 日本語丸めフォーマット
    japanese_format : function (size, dec, separate) {
        units = [
            {unit: '',   threshold: 0},
            {unit: '', threshold: 10000},
            {unit: '', threshold: 10000 ** 2},
            {unit: '', threshold: 10000 ** 3}
        ];
        return this.custom_format(size, units, dec, separate);
    }
};
5
3
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
5
3