背景
メッセージ表示のコードで、数字が埋め込んであったので、変数から変換させたいと思った。
DateTimeFormat を先日学習したばかりだったので、まさに出番だと調べてみた記録
結論
全角
const localeFullwide = new Intl.Locale(
'ja-jp',
{
numberingSystem: "fullwide"
}
);
console.log(new Intl.NumberFormat(localeFullwide.toString()).format(1234567890));
結果はこんな感じ
1,234,567,890
漢数字
const localeHanidec = new Intl.Locale(
'ja-jp',
{
numberingSystem: "hanidec"
}
);
console.log(new Intl.NumberFormat(localeHanidec.toString()).format(1234567890));
結果はこんな感じ
一,二三四,五六七,八九〇
補足
Intl.Locale.toString()
locale に設定出来る文字列を出力してくれる。
例)
ja-JP-u-nu-fullwide
ja-JP-u-nu-hanidec
numberingSystem の様々な例
const numberingSystems = ["arab", "arabext", "bali", "beng", "deva", "fullwide", "gujr", "guru", "hanidec", "khmr", "knda", "laoo", "latn", "limb", "mlym", "mong", "mymr", "orya", "tamldec", "telu", "thai", "tibt"];
const cons = numberingSystems.map((n) => {
console.log(
new Intl.NumberFormat(
new Intl.Locale(
'ja-jp', {
numberingSystem: n
}).toString()
).format(1234567890)
);
});
世界ってすごいねって感じになります・・。結局使えそうなのは、fullwide/handic しかなさそうって結論
١٬٢٣٤٬٥٦٧٬٨٩٠
۱٬۲۳۴٬۵۶۷٬۸۹۰
᭑,᭒᭓᭔,᭕᭖᭗,᭘᭙᭐
১,২৩৪,৫৬৭,৮৯০
१,२३४,५६७,८९०
1,234,567,890
૧,૨૩૪,૫૬૭,૮૯૦
੧,੨੩੪,੫੬੭,੮੯੦
一,二三四,五六七,八九〇
១,២៣៤,៥៦៧,៨៩០
೧,೨೩೪,೫೬೭,೮೯೦
໑,໒໓໔,໕໖໗,໘໙໐
1,234,567,890
᥇,᥈᥉᥊,᥋᥌᥍,᥎᥏᥆
൧,൨൩൪,൫൬൭,൮൯൦
᠑,᠒᠓᠔,᠕᠖᠗,᠘᠙᠐
၁,၂၃၄,၅၆၇,၈၉၀
୧,୨୩୪,୫୬୭,୮୯୦
௧,௨௩௪,௫௬௭,௮௯௦
౧,౨౩౪,౫౬౭,౮౯౦
๑,๒๓๔,๕๖๗,๘๙๐
༡,༢༣༤,༥༦༧,༨༩༠
numberingSystem で使える一覧はここから取得
実際にはもっとたくさんあるみたいだけど
あとがき
ほんとは、Intl.NumberFormat の options として、numberingSystem を指定して生成したかったが・・
こんな感じで、TypeScript 上だとエラーになってしまう。(JavaScriptでなら問題なし)
で、本当は Declaration Merging を利用して、options として使えるようにしたかったんだが・・
TypeScript 初心者には敷居が高かったので、現時点では諦め。
Local なら問題なかったので、LocalString を生成して利用することにしたのが今回の内容
ってことで、options の Declaration Merging はこうすればいいよってのがわかる人がいたら教えてください。