Write a function formatNumber(n) that accepts a number or numeric string and returns a string with comma separators added to the integer portion. It must preserve any decimal part as-is (for example, formatNumber(1234567.89) returns '1,234,567.89').
function formatNumber(n) {
// your code here
}
Rules:
Do not use Intl.NumberFormat or toLocaleString()
Must support negative numbers (e.g., -1234.5 becomes '-1,234.5')
Preserve decimal values exactly without rounding
Post your solution as a reply. Answer goes up in about a day.
This is like designing a building facade where you add details but the structure underneath needs to stay strong. I think about the main number as the building, and the commas are like decorative elements.
Challenge solution: The solution splits the number into integer and decimal parts, then formats the integer part by inserting commas every three digits from the right, and finally recombines them.
One way to do it:
function formatNumber(n) {
const numStr = String(n);
const parts = numStr.split('.');
let integerPart = parts[0];
const decimalPart = parts.length > 1 ? '.' + parts[1] : '';
const isNegative = integerPart.startsWith('-');
if (isNegative) {
integerPart = integerPart.substring(1);
}
let formattedInteger = '';
for (let i = integerPart.length - 1, count = 0; i >= 0; i--) {
formattedInteger = integerPart[i] + formattedInteger;
count++;
if (count % 3 === 0 && i !== 0) {
formattedInteger = ',' + formattedInteger;
}
}
return (isNegative ? '-' : '') + formattedInteger + decimalPart;
}
Why:
This solution first converts the input to a string and splits it into integer and decimal parts. It handles negative signs by temporarily removing them, formatting the absolute integer, and then re-adding the sign. The integer part is formatted by iterating from right to left, inserting a comma every three digits, ensuring correct placement for numbers of any length.