6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPで万とか億とかつける感じの

Last updated at Posted at 2014-07-07

ザックリと作ってみた万とか億とかつけるアレ
桁ごとの変数作るのはなんとなくやだったので…
4の倍数桁になるように左側から0詰めして、四桁毎に配列化してゴニョります。
肥大化してしまったのが難(´・ω:;.:...
一応事故防止のためにPHP_INT_MAXは超えないようにしてます
表示用に早々そんな桁数使うこたー無いはずなので…
主に金額用だから国家予算超えちゃうし笑

roundnumber.php
	public static $roundNumbers = array('', '万', '億', '兆', '京', '垓', '杼');

	public static function toRoundNumberFormat($amount, $options = array()) {
		$defaultOptions = array(
			'useThousand' => true,
			'unit' => ''
		);
		$options = array_merge($defaultOptions, $options);

		if (empty($amount) || !is_numeric($amount) || $amount > PHP_INT_MAX) {
			return 0 . $options['unit'];
		}

		if (!ctype_digit((string)$amount)) {
			$amount = floor($amount);
		}

		$characters = mb_strlen($amount);
		$restCharacters = $characters % 4;
		if ($restCharacters > 0) {
			$pad = $characters;
			while ($pad % 4 !== 0) {
				$pad++;
			}
			$amount = str_pad($amount, $pad, '0', STR_PAD_LEFT);
		}

		$spritAmout = str_split($amount, 4);

		$count = count($spritAmout);
		$roundNumbers = array();
		for ($i = 1; $i <= $count; $i++) {
			$roundNumbers[$i] = self::$roundNumbers[$i];
		}

		$result = 0;
		if (!empty($roundNumbers)) {
			$tmpResult = array();
			$spritAmout = array_reverse($spritAmout);
			foreach ($spritAmout as $k => $v) {
				$number = intval($v);
				$roundNumber = (isset($roundNumbers[$k])) ? $roundNumbers[$k] : '';
				if ($k == 0) {
					if ($options['useThousand'] === true && $v !== '0000') {
						$tmpResult[] = $number;
					}
					continue;
				}
				if ($v !== '0000') {
						$tmpResult[] = $number . $roundNumber;
				}
			}
			$result = implode('', array_reverse($tmpResult));
			if (empty($result)) {
				$result = 0;
			}
		}
		return $result . $options['unit'];
	}

6
5
0

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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?