How to sum numbers with formats like N.NNNN,NN in JavaScript

Viewed 251

Well, long story short. I'm looking for a way to sum numbers with comma for decimals and thousand seperator.

Currently, I'm trying to format the number with

sumamount += parseFloat(this.value.replace(/,/g,''));

it sill not working correctly.

Is there another way then removing the dot, replacing , with . and in the end reversing the change again? Thank you very much!

so, this is working, but... not really pretty nor performant, is it?

sumamount += parseFloat(this.value.replace('.', '').replace(',', '.'));
3 Answers

A clean way would be to use currency.js (1.1kB Gziped)

const FORMAT = { separator: '.', decimal: ',' };

const v1 = currency('140.504,99', FORMAT);
const v2 = currency('24.207,56', FORMAT);

then,

v1.add(v2)

Output

164712.55

Or,

v1.add(v2).format()

gives

164.712,55

You have to do ugly string operations to convert a number-like string like this to Float/Number. To 'reverse the change' you may want to try Number.toLocaleString for your own locale (see MDN for that).

const someValue = "200.204,23";
const toNumber = Number(someValue.split(".").join("").split(",").join("."));
console.log(toNumber);
console.log(toNumber.toLocaleString("NL-nl"));
.as-console-wrapper { top: 0; max-height: 100% !important; }

You can also convert the numbers into their original formats then do what ever you wish to do with them. Like this:

let rev = (a)=>
{
    // r is the real number
    let r = 0;

    a = a.split(",").reverse();

    for(let i = 0; i < a.length; i++)
    {
        r += Number(a[i]) * Math.pow(1000,i);
    }

    return r;
}

let sum = (a,b)=>
{
    return (rev(a) + rev(b));
}

console.log(sum("2,100","1,000.10")); //3100.1
Related