[JavaScript] 一则面试题和number.toLocaleString

今天在群里,有人说了一到面试题,把一串正整数数字变成除以100后的三个三个数字,用,分割的形式。

比如:

f(123456789)="1,234,567.89";
f(0)='0.00'

于是我随手写了个代码

// 把数组xs按照n为长度分组
const splitEvery = n => xs => xs.length > n ? [xs.slice(0,n),...splitEvery(n)(xs.slice(n))] :[xs]

// 把数组xs按照n为长度,从尾部开始分组
const splitEveryFromTail = n => xs => splitEvery(n)(xs.reverse()).map(x=>x.reverse()).reverse();

const f = (n)=>{
    const ss=n.toString(); // 转换为字符串
    const s = ss.length === 1 ? '00' + ss : ss.length === 2 ? '0' + ss : ss; //补足前导0,让长度至少为3
    const cents = s.slice(-2); // 分,我把它当钱来看啦
    const yuans = s.slice(0,-2); // 元,我把它当钱来看啦
    return splitEveryFromTail(3)([...yuans]).map(x=>x.join('')).join(',') + '.' + cents;
}

然后有人说了一个更好的办法,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

我还是图样啊。

你可能感兴趣的:([JavaScript] 一则面试题和number.toLocaleString)