九十月份,在我的面试经历中,这道题算是比较高频的了,都是出现在初次视频面试的过程中
得到一个number类型数据,将小数点前面的部分从右到左用“,”每三位隔开
例如
输入 12344.2222
输出 12,344.2222
输入 344.2222
输出 344.2222
输入 -2344.2222
输出 -2,344.2222
这里需要说的是最后一步
- 既然是将数据从右到左每三位加一个逗号,这里想到的是先将数据每一位隔开成数组,然后再反转
- 最后用到的是reduce来累加,达成一个字符串拼接的效果
再来解释一下reduce
reduce((pre, next, index)=>{
return (index % 3 ? next : next + ',') + pre
});
const convert = money => {
if(typeof money !== 'number') return new Error('请输入正确的格式!');
let num; // 小数点前面的部分
const value = String(money).split('.')[1]; // 小数点后面的部分
const flag = String(money).indexOf('-') > -1; // 是否为负数
let result;
if(flag){
num = String(money).split('-')[1].split('.')[0];
}else{
num = String(money).split('.')[0];
}
// 先转数组 再反转 然后reduce判断位置累加
result = num.split('').reverse().reduce((pre, next, index)=>{
return (index % 3 ? next : next + ',') + pre
});
// 拼接小数点后面的部分
if(value){
result = result + '.' + value;
}
// 负数加上‘-’
if(flag){
result = '-' + result;
}
return result
}