今天在群里纱昧,有人說(shuō)了一到面試題户矢,把一串正整數(shù)數(shù)字變成除以100后的三個(gè)三個(gè)數(shù)字虏肾,用,
分割的形式冠蒋。
比如:
f(123456789)="1,234,567.89";
f(0)='0.00'
于是我隨手寫了個(gè)代碼
// 把數(shù)組xs按照n為長(zhǎng)度分組
const splitEvery = n => xs => xs.length > n ? [xs.slice(0,n),...splitEvery(n)(xs.slice(n))] :[xs]
// 把數(shù)組xs按照n為長(zhǎng)度羽圃,從尾部開(kāi)始分組
const splitEveryFromTail = n => xs => splitEvery(n)(xs.reverse()).map(x=>x.reverse()).reverse();
const f = (n)=>{
const ss=n.toString(); // 轉(zhuǎn)換為字符串
const s = ss.length === 1 ? '00' + ss : ss.length === 2 ? '0' + ss : ss; //補(bǔ)足前導(dǎo)0,讓長(zhǎng)度至少為3
const cents = s.slice(-2); // 分抖剿,我把它當(dāng)錢來(lái)看啦
const yuans = s.slice(0,-2); // 元朽寞,我把它當(dāng)錢來(lái)看啦
return splitEveryFromTail(3)([...yuans]).map(x=>x.join('')).join(',') + '.' + cents;
}
然后有人說(shuō)了一個(gè)更好的辦法,toLocalString()
const f = (n) => (n/100).toLocalString();
而且文檔里還介紹了更多好玩的用法斩郎,比如:
var number = 123456.789;
// request a currency format
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// → 123.456,79 €
// the Japanese yen doesn't use a minor unit
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// → ¥123,457
// limit to three significant digits
console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// → 1,23,000
// Use the host default language with options for number formatting
var num = 30000.65;
console.log(num.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
// → "30,000.65" where English is the default language, or
// → "30.000,65" where German is the default language, or
// → "30 000,65" where French is the default language
我還是圖樣啊脑融。