LoginSignup
0
0

More than 5 years have passed since last update.

C#で漢数字表記

Last updated at Posted at 2017-09-21

数値を桁数ごとに分解

        /// <summary>
        /// 数値を桁数ごとに分解
        /// </summary>
        /// <param name="n">数値</param>
        /// <param name="place">桁</param>
        /// <returns></returns>
        protected List<BigInteger> SplitNumber(BigInteger n, int place)
        {
            var list = new List<BigInteger>();

            //累乗
            var sunit = (BigInteger)Pow(10, place);

            for (; n > 0; n /= sunit)
            {
                var x = (n % sunit);
                list.Add(x);
            }
            return list;
        }

Powでは10の桁乗を出している。Math.Powだとdoubleになってしまうので自作している。
これで指定桁ごとに分割された数字のリストが作成される

区切られた数値に単位をつける

        /// <summary>
        /// 区切られた数値に単位をつける(万とか兆とか)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">区切られた数値のリスト</param>
        /// <returns></returns>
        protected virtual List<string> FormatStringList<T>(IList<T> list) where T : IEquatable<T>
        {
            var str = new List<string>();
            str.Add(list[0].ToString());

            for (int i = 1; i < list.Count; i++)
            {
                if (list[i].Equals(default(T)) == true) //0の場合は空文字列をセット
                {
                    str.Insert(0, "");
                }
                else
                {
                    str.Insert(0, list[i].ToString() + unit[i - 1]);
                }
            }

            return str;
        }
protected override string[] unit { get; set; }
            = new string[] { "万", "億", "兆", "京", "垓", "秭", "穣", "溝", "澗", "正",
            "載", "極 ", "恒河沙", "阿僧祇", "那由他", "不可思議", "無量大数" };

という単位文字列を派生クラスで定義することによって単位つき数字文字列のリストができる。
これを連結すれば漢数字文字列が作れる

ソースコード

https://github.com/reniris/NumberText/tree/master
とりあえず使ってみればわかるはず
派生クラスを作ってプロパティ実装すれば英語とかSI接頭辞とかに対応できます。

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