如何用JavaScript计算数字中千、百、十、个位的对应数量?
数字拆分:返回千位组数、百位、十位、个位组成的数组
要实现你需要的功能,不能用Math.round()(它会四舍五入,不适合取位场景),正确的做法是结合整除取整和取余运算,直接提取对应位的数值:
实现代码
function splitNumber(num) { // 计算千的数量:数字整除1000 const thousands = Math.floor(num / 1000); // 先取除以1000的余数,再整除100得到百位 const hundreds = Math.floor((num % 1000) / 100); // 取除以100的余数,再整除10得到十位 const tens = Math.floor((num % 100) / 10); // 取除以10的余数得到个位 const units = num % 10; return [thousands, hundreds, tens, units]; } // 测试示例 console.log(splitNumber(73284)); // 输出 [73, 2, 8, 4]
代码说明
- 千位数量:
num / 1000得到带小数的结果,Math.floor()舍去小数部分,直接得到千位的组数 - 百位数量:先用
num % 1000提取出后三位数字,再除以100取整,得到百位的数值 - 十位数量:用
num % 100提取出后两位数字,除以10取整得到十位数值 - 个位数量:直接用
num % 10提取最后一位数字
如果习惯更简洁的写法,对于正数可以用~~运算符代替Math.floor()(效果一致),代码可简化为:
function splitNumber(num) { const thousands = ~~(num / 1000); const hundreds = ~~((num % 1000) / 100); const tens = ~~((num % 100) / 10); const units = num % 10; return [thousands, hundreds, tens, units]; }
内容的提问来源于stack exchange,提问作者CodeNinja
相关产品推荐
相关产品推荐

