0

I'm trying to create a simple program that will allow the user to input numbers or words and have them sorted alphabetically (in case of words) or numerically (in case of numbers). For this I need an input that will differentiate between numbers and words so that for example 10, -10, 0.5 and -0.5 will be evaluated as numbers and everything else will be considered words.

So far I have come up with this:

function recordUserInput() {
  userInput = $('input').val();

  if (userInput.charAt(0).match(/^(-)?[0-9]/)) {
    console.log('number', userInput);
  }
  else {
    console.log('text', userInput);
  }

}

However, negative numbers are still evaluated as text.

What am I doing wrong?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
broccoli
  • 3
  • 3
  • I really think Joseph's answer is the best approach rather than regex. However, the reason your regex didn't work was because you used `charAt(0).match` against your regex. In the case of negative numbers, `charAt(0)` is `-`, so it will never match against `^(-)?[0-9]`. You should have simply used `userInput.match` – Aserre Nov 28 '16 at 13:42

4 Answers4

3

Use the unary +. If it returns NaN, it's not a number.

var type = isNaN(+userInput) ? 'text' : 'number';

parseFloat is probably not optimal. It parses left to right looking for a number and stops on a non-number. What it gathers, it turns to a number. parseFloat('123a') === 123.

Joseph
  • 117,725
  • 30
  • 181
  • 234
0

Don't use .charAt(0) because you only look at the first character. Instead your regular expression is intended to look at the whole input, so just do (but add the + and $ at the end):

if (userInput.match(/^-?[0-9]+$/)) {

Once you have put the inputs in an array, you can sort it like this (which also demonstrates how to better test for numbers):

// Sample input:
var inputs = ['z', 1, 'a', 9, 3];

inputs.sort(function (a, b) {
    return isNaN(a) - isNaN(b) || isNaN(a) && a.localeCompare(b) || +a - +b;
});

console.log(inputs);
trincot
  • 317,000
  • 35
  • 244
  • 286
0

You can write a small function isNumeric() to properly determine is a value is numeric. This is similar to the solution proposed in https://stackoverflow.com/a/9716488/1637175

function isNumeric(val) {
    return !isNaN(parseFloat(val)) && isFinite(val);
}

Your original function becomes

function recordUserInput() {
    userInput = $('input').val();

    if ( isNumeric(userInput) ) {
        console.log('number', userInput);
    }
    else {
        console.log('text', userInput);
    }
}
Community
  • 1
  • 1
thekenobe
  • 469
  • 6
  • 10
0

If you want to check if an user input is a number or not, you can use something like this:

/^[-+]?\d+\.?\d*$/

it will match all number which might contain - or + at the beginning and dot symbol. Number like 10,-10.0 and +10.0 Example

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53