Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to convert a string with either, or . as decimal/thousand separators into a float in JavaScript

1 Answer

0 votes
function toFloat(localFloatStr) {
    // Count dots and commas
    const commaCount = (localFloatStr.match(/,/g) || []).length;
    const dotCount = (localFloatStr.match(/\./g) || []).length;

    let normalized = localFloatStr;

    if (commaCount && dotCount) {
        // Assume the separator closest to the right is the decimal
        if (localFloatStr.lastIndexOf(',') > localFloatStr.lastIndexOf('.')) {
            normalized = localFloatStr.replace(/\./g, '').replace(',', '.');
        } else {
            normalized = localFloatStr.replace(/,/g, '');
        }
    } else if (commaCount) {
        // Only commas — assume commas are decimal
        normalized = localFloatStr.replace(/\./g, '').replace(',', '.');
    } else {
        // Only dots — assume dots are decimal
        normalized = localFloatStr.replace(/,/g, '');
    }

    return parseFloat(normalized);
}


console.log(toFloat('1,223,455.678')); 
console.log(toFloat('1.223.455,678'));
console.log(toFloat('2.453,78')); 
console.log(toFloat('2,453.78')); 


/*
run:

1223455.678
1223455.678
2453.78
2453.78

*/

 



answered Jun 27, 2025 by avibootz
...