Using JSX syntax I wrote a function that takes either a float or an integer as a parameter and returns a formatted string. I'd like any feedback for refactoring the code.
const moneyFormat = (float) => {
let answer = [];
let firstHalf;
let secondHalf;
// check if whole number
if (float % 1 === 0) {
float = Math.trunc(float);
firstHalf = float.toString();
secondHalf = '.00';
} else {
float = float.toFixed(2);
const splitNumArr = float.split('.');
firstHalf = splitNumArr[0];
secondHalf = '.' + splitNumArr[1];
}
let everyThree = 0;
// push chars into answer array
for (let i = firstHalf.length - 1; i >= 0; i--) {
answer.push(firstHalf[i]);
everyThree += 1;
// insert space for every three chars
if (everyThree % 3 === 0) {
answer.push(' ');
}
}
// reverse array and add secondHalf
answer = answer.reverse().join('') + secondHalf;
return answer;
}
console.log(moneyFormat(2310000.159897)); // '2 310 000.16'
console.log(moneyFormat(1600)); // '1 600.00'