Converting String to Number with our loved one - JavaScript

Since I love JavaScript a lot, it happens quite often to have the need to convert String to Number.

And because whichever function I use I always have problems here's a comparison between several converting options and which one is the best.
In order to get the best results I'll try to convert to Float instead of Int.

JavaScript

Test cases and expected results:

  1. 123.4 --- 123.4
  2. "123.4" --- 123.4
  3. "0123.4" --- 123.4
  4. "123.4x5" --- 123.4
  5. "123.4.5" --- 123.4
  6. "" --- 0
  7. "-0" --- 0
  8. "0.0" --- 0.0
  9. "-123.4x" --- -123.4
  10. "1.2-3.4" --- 1.2
  11. NaN --- 0
  12. "10px" --- 10
  13. null --- 0
  14. "test" --- 0
  15. 0x10 --- 16
  16. undefined --- 0
  17. {} --- 0
  18. [] --- 0
  19. [{}] --- 0
  20. "undefined" --- 0

And a list of the different ways to convert to Number that I know or managed to find.

  1. Number(x)
  2. parseFloat(x)
  3. x | 0
  4. x >> 0
  5. x << 0
  6. ~ ~ x
  7. + x
  8. x + 0
  9. x * 1
  10. x / 1

10 methods vs 20 test cases

Test code:

var test_cases = [123.4, "123.4", "0123.4", "123.4x5", "123.4.5", "", "-0", "0.0", "-123.4x", "1.2-3.4", NaN, "10px", null, "test", 0x10, undefined, {}, [], [{}], "undefined"],
    expected_results = [123.4, 123.4, 123.4, 123.4, 123.4, 0, 0, 0.0, -123.4, 1.2, 0, 10, 0, 0, 16, 0, 0, 0, 0, 0],
    test_functions = [
        function(x){ return Number(x); },
        function(x){ return parseFloat(x); },
        function(x){ return x | 0; },
        function(x){ return x >> 0; },
        function(x){ return x << 0; },
        function(x){ return ~~ x; },
        function(x){ return + x; },
        function(x){ return x + 0; },
        function(x){ return x * 1; },
        function(x){ return x / 1; }
    ],
    test_passes = [];

for(var i in test_functions){
    var test = test_functions[i],
        passes = 0;

    for(var j in test_cases){
        var test_case = test_cases[j],
        expected_result = expected_results[j];

        if(test(test_case) === expected_result){
            passes++;
        }
    }

    test_passes[i] = passes;

    console.log('test: ' + test, '; result: ' + passes);
}

Results:

test_passes: [9, 11, 12, 12, 12, 12, 9, 3, 9, 9]

What?

No way to get the right results with all these functions?

Taking a look into the detailed results and with several more console.logs and tests I finally managed to get the right way for converting String to Number.

And the solution is:

parseFloat(x) || 0

parseFloat(x) || 0 passed all the tests and seems to be the perfect solution so far.

Thank you, JavaScript, for making my life interesting! :)

Lucky giraffe