delliottg
delliottg

Reputation: 4140

How to test for multiple decimal points?

I'm writing unit tests for a function that's supposed to return a float. I'm trying to prevent someone from sending a set of characters (notice I didn't say string) to the function, like 3.2.1. If I use the normal tests for this "number", they all seem to fail with:

Uncaught SyntaxError: missing ) after argument list.

EG:

I suppose I could wrap it in quotes and test it as a string (all the tests above work as expected when the predicate is a string).

Various SO questions that haven't answered this one:

So, the actual question: how can I test for a 'number' that has multiple decimal points and reject it?

Here's my actual code where most of the tests run successfully:

/**
* 
* @param {*} value 
* Converts a numeric string value to a float for use by a timeout interval
* datatype: ParseTimeoutInterval(string)
* example: ParseTimeoutInterval('2.5')
* return type: float
* return example: 2.5
*/
SerialWidget.prototype.ParseTimeoutInterval = function (value) {

try {
    var self = this;

    self.CallListeners('debug', 'ParseTimeoutInterval: value = ' + value);

    if (value) {
        var result = parseFloat(value);
        if(result < 0 || isNaN(result)){
            self.CallListeners('debug', 'ParseTimeoutInterval: value is negative or NaN');
            return null;            
        }
    return result.toPrecision(2);

    } else {
        return null;    
    }
    self.CallListeners('debug', 'ParseTimeoutInterval: value is not a number');
    return null;

} catch (ex) {
    self.OnError('ParseTimeoutInterval', ex.message);
}
};

Upvotes: 0

Views: 1255

Answers (1)

mccambridge
mccambridge

Reputation: 1022

Assuming you're good with checking a string, you could then split it into an array and check the length.

var badNumber = '3.2.1';
if (badNumber.split('.').length > 2) {
    console.error('uh oh. THAT\'s not a number!');
} else {
    // proceed
}

Upvotes: 2

Related Questions