钱币格式转换函数

//钱币格式转换函数
//传入一串数字,转换为带有逗号分隔符的形式
//例如 12345 → 12,345
let readline = require('readline-sync');
console.log('请输入要转换的数字:');
let money = readline.question(); // 例如输入:12345
function change(money) {
let str = "";
// 从右数的第一位开始 从右到左进行计算
for (let i = money.length - 1; i >= 0; i--) {
str += money[money.length - 1 - i];
if (i % 3 == 0 && i != 0) {
str += ",";
}
}
return str;
}
console.log(change(money));
// 1 2 3 4 5
// 1 2,3 4 5

猜你喜欢

转载自www.cnblogs.com/dbda/p/11407319.html