There are many times in JavaScript when you need to scrub the input and give output of a specific type. Today, I will cover how you can convert anything into a number. The function to do so is as follows:

// Converts any object into a number.
function parseNumber(obj) {
return parseFloat(obj)||+obj||0;
}

Now the question is, what happens under different circumstances. Look at (or even try out) the following to find out:

// Convert any empty string into a number:
var a = "";
var b = parseNumber(a);  // 0
alert(JSON.stringify(a) + "\n" + b);

// Convert a string version of a number into a number:
var a = "9563.49";
var b = parseNumber(a);  // 9563.49
alert(JSON.stringify(a) + "\n" + b);

// Convert a string starting with space and then a number with extra decimal points into a number:
var a = "    9563.49.2";
var b = parseNumber(a);  // 9563.49
alert(JSON.stringify(a) + "\n" + b);

// Convert a sentence into a number:
var a = "I am 23.";
var b = parseNumber(a);  // 0
alert(JSON.stringify(a) + "\n" + b);

// Convert an array of numbers into a number:
var a = [129,84,7];
var b = parseNumber(a);  // 129
alert(JSON.stringify(a) + "\n" + b);

// Convert a date into a number:
var a = new Date();
var b = parseNumber(a);  // milliseconds since January 1, 1970
alert(JSON.stringify(a) + "\n" + b);

// Convert an object literal into a number:
var a = {};
var b = parseNumber(a);  // 0
alert(JSON.stringify(a) + "\n" + b);

The most interesting of the above test are probably the parsing of dates and arrays. For dates, the number will be the amount of milliseconds since January 1, 1970. For arrays, the number will be the numeric value of the number in the first position of the array.

Categories: BlogJavaScriptJScript