34

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.

3
  • 2
    Are there .s when the number is greater than 999? Commented Aug 23, 2013 at 14:22
  • 2
    Keep in mind that replace returns a new string. Commented Aug 23, 2013 at 14:23
  • 1
    Please post the full code using replace. That should be sufficient so there must be something else wrong. Commented Aug 23, 2013 at 14:24

3 Answers 3

37

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Fails with 111.222.3333,44. demo. .replace only replaces the first match unless you have a global regular expression. edit: whoops messed up the input string
@FakeRainBrigand Thanks, I updated my code.. not really good with regular expressions, does that seem right to you?
Yeah, that's exactly right (I had it wrong in my original fiddle)
This solution works for "nice" users but validation needs to work even for "bad" users. If you have the following (for example) this passes when it shouldn't: var testNumber = "10.0.0,000";
33
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});

2 Comments

With this answer 123,4 gives you 1234 for the parse, and 1234.00 for the localisation. It's not answering the question, which is parsing comma decimal separators.
Using toLocaleString is the best option for me, thank you.
9

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.