**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.

**Test cases and expected results:**

- 123.4 --- 123.4
- "123.4" --- 123.4
- "0123.4" --- 123.4
- "123.4x5" --- 123.4
- "123.4.5" --- 123.4
- "" --- 0
- "-0" --- 0
- "0.0" --- 0.0
- "-123.4x" --- -123.4
- "1.2-3.4" --- 1.2
- NaN --- 0
- "10px" --- 10
- null --- 0
- "test" --- 0
- 0x10 --- 16
- undefined --- 0
- {} --- 0
- [] --- 0
- [{}] --- 0
- "undefined" --- 0

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

- Number(x)
- parseFloat(x)
- x | 0
- x >> 0
- x << 0
- ~ ~ x
- + x
- x + 0
- x * 1
- 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! :)**