Paepoi » JavaScript Tips » JavaScript Intl
JavaScript Intl
# 最終更新日 2024.01.03
NumberFormat
数値表現の国際化
#!/usr/bin/gjs
const LANG = Intl.getCanonicalLocales('ja-jp');
console.log(LANG);
//=> ja-JP
// 未指定でも勝手にカンマ区切りになる、少数は有効な値以外は無視される
console.log(new Intl.NumberFormat(LANG, {
}).format(12300.6000));
//=> 12,300.6
// 通貨
console.log(new Intl.NumberFormat(LANG, {
style: 'currency',
currency: 'JPY'
}).format(5000));
//=> ¥5,000
// ゼロ詰め、カンマ区切りを殺す必要あり
console.log(new Intl.NumberFormat(LANG, {
minimumIntegerDigits: 5,
useGrouping: false
}).format(21));
//=> 00021
// パーセント、下二桁以降は四捨五入される
console.log(new Intl.NumberFormat(LANG, {
style: 'percent'
}).format(0.345));
//=> 35%
DateTimeFormat
Date を使って表現するより簡単、なのか???
#!/usr/bin/gjs
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
console.log(new Intl.DateTimeFormat('en-US').format(date)); //=> 12/20/2012
console.log(new Intl.DateTimeFormat('ja-JP').format(date)); //=> 2012/12/20
// オプションで指定したものだけ表示
console.log(new Intl.DateTimeFormat('ja-JP', {
year: 'numeric',
weekday: 'long',
era: 'long'
}).format(date)); //=> 西暦2012年 木曜日
RelativeTimeFormat
時間や日付の差異を国際化
#!/usr/bin/gjs
const LANG = Intl.getCanonicalLocales('ja-jp');
const rtf = new Intl.RelativeTimeFormat(LANG, {
numeric: 'auto'
});
for (let i=-3; i<4; i++) {
console.log(rtf.format(i, 'day')); // hour や year 等指定は Date を見て
}
/* output
3 日前
一昨日
昨日
今日
明日
明後日
3 日後
*/
Copyright(C) sasakima-nao All rights reserved 2002 --- 2025.