Parsing numbers with a comma decimal separator in JavaScript

I used this function to check if a value is a number:

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

My program need to work with German values. We use a comma as the decimal separator instead of a dot, so this function doesn't work.

I tried to do this:

n.replace(",",".")

But it also doesn't seem to work. The exact function I tried to use is:

function isNumber(n) {
    n=n.replace(",",".");
    return !isNaN(parseFloat(n)) && isFinite(n);
}

The number looks like this 9.000,28 instead of the usual 9,000.28 if my statement wasn't clear enough.

Answers:

Answer

You need to replace (remove) the dots first in the thousands separator, then take care of the decimal:

function isNumber(n) {
    'use strict';
    n = n.replace(/\./g, '').replace(',', '.');
    return !isNaN(parseFloat(n)) && isFinite(n);
}
Answer
var number = parseFloat(obj.value.replace(",",""));

You'll probably also want this to go the other way...

obj.value = number.toLocaleString('en-US', {minimumFractionDigits: 2});
Answer

I believe the best way of doing this is simply using the toLocaleString method. For instance, I live in Brazil, here we have comma as decimal separator. Then I can do:

var number = 10.01;
console.log(number)
// log: 10.01

console.log(number.toLocaleString("pt-BR"));
// log: 10,01

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.