Hey folks, I’m having trouble with a custom function I made for my Zapier app. It’s supposed to format numbers, but it’s not working as expected.
Here’s what I’m dealing with:
function formatMyNumber(num) {
let cleaned = num.toString().replace(/,/g, '.');
let lastDot = cleaned.lastIndexOf('.');
let decimals = cleaned.slice(lastDot);
let wholeNum = cleaned.slice(0, lastDot).replace(/[^0-9]/g, '');
return Number(wholeNum + decimals);
}
console.log(formatMyNumber('50,00'));
I thought this would give me 50
, but I’m getting 5000
instead. Any ideas on what I’m doing wrong here? I’m scratching my head trying to figure out why it’s adding those extra zeros. Thanks for any help!
I’ve run into similar issues when working with number formatting in JavaScript, especially when dealing with different locale formats. Your function is actually working as designed, but there’s a small oversight.
The problem is that you’re replacing commas with dots, which changes ‘50,00’ to ‘50.00’. Then, when you use Number() to convert it, JavaScript interprets this as 50 with two decimal places.
To fix this, you could modify your function to remove all non-numeric characters except the last decimal point. Here’s a quick adjustment:
function formatMyNumber(num) {
let cleaned = num.toString().replace(',', '.');
let parts = cleaned.split('.');
return Number(parts[0] + (parts.length > 1 ? '.' + parts[1] : ''));
}
This should give you the expected output of 50 for the input ‘50,00’. It handles both comma and dot as decimal separators, which is handy for different locales. Just be cautious with larger numbers that might use commas as thousand separators.
I’ve encountered this issue before, and it’s a common pitfall when dealing with number formatting across different locales. The problem in your code is that you’re replacing all commas with dots, which alters the number’s structure.
Here’s a more robust approach:
function formatMyNumber(num) {
let cleaned = num.toString().replace(/[^
\d,\.]/g, '');
let parts = cleaned.split(/[,\.]/);
return Number(parts[0] + (parts.length > 1 ? '.' + parts[1] : ''));
}
This function removes all non-numeric characters except commas and dots, then splits the string at either comma or dot. It preserves the whole number part and adds the decimal part if it exists. This should correctly handle inputs like ‘50,00’ or ‘1.234,56’, returning 50 and 1234.56 respectively.
Remember to test thoroughly with various inputs to ensure it meets all your use cases.
hey, i’ve seen this before! the issue is ur treating ‘,’ like a decimal point. try this:
function formatMyNumber(num) {
return Number(num.replace(',', '.'));
}
This should work for most cases. it just swaps the comma for a dot n lets Number() do its thing. simple but effective!