0
0

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 1 year has passed since last update.

PHPで数値を漢数字に変換

Last updated at Posted at 2023-09-02

1~9999までの数字を漢数字に変換するプログラムが必要になったため、
今後必要になる可能性も考慮しての備忘になります。

numberToKanji.php
function numberToKanji($number) {
    $kanjiDigits = array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
    $kanjiUnits = array('', '十', '百', '千');
    $kanjiBigUnits = array('', '万', '億', '兆', '京'); // 追加の大字を必要に応じて増やすことができます

    if (!is_numeric($number) || $number < 0 || $number > 9999) {
        return '無効な入力';
    }

    $kanji = '';
    $numberStr = strval($number);
    $numberLen = strlen($numberStr);

    for ($i = 0; $i < $numberLen; $i++) {
        $digit = intval($numberStr[$i]);
        $unit = $numberLen - $i - 1;

        if ($digit !== 0) {
            if ($unit === 1 && $digit === 1) {
                $kanji .= $kanjiUnits[$unit]; // 十の場合は「十」を追加しない
            } elseif ($unit === 2 && $digit === 1) {
                $kanji .= '百'; // 百の場合は「一百」ではなく「百」と表示
            } elseif ($unit === 3 && $digit === 1) {
                $kanji .= '千'; // 千の場合は「一千」ではなく「千」と表示
            } else {
                $kanji .= $kanjiDigits[$digit] . $kanjiUnits[$unit];
            }
        } elseif ($unit === 0 && $numberLen === 1) {
            $kanji .= $kanjiDigits[0]; // ゼロの場合
        }

        // 大字を追加する
        if ($unit % 4 === 0 && $unit > 0) {
            $kanji .= $kanjiBigUnits[$unit / 4];
        }
    }

    return $kanji;
}
0
0
3

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?