19
var str = '0.25';

How to convert the above to 0.25?

user198729
  • 61,774
  • 108
  • 250
  • 348
  • `parseInt` is blazing fast, but if you need decimals, you should go with `parseFloat`: https://jsbench.me/pokty2hchw/1 – Xairoo Sep 24 '21 at 08:03
  • `'0.25'*1` is about 98% faster than `parseFloat()` https://jsbench.me/bflb5lcqpw/1 – Miro Dec 01 '22 at 21:32
  • 1
    @Miro beware benchmarks against trivial single-value cases. The methods don't scale the same. Performing the same comparison on an array of 10 values at once, `parseFloat()` performs about 15% better than `''*1`: https://jsbench.me/c8ldyhrth3/1 – Will Feb 10 '23 at 12:18

4 Answers4

42

There are several ways to achieve it:

Using the unary plus operator:

var n = +str;

The Number constructor:

var n = Number(str);

The parseFloat function:

var n = parseFloat(str);
Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
6

For your case, just use:

var str = '0.25';
var num = +str;

There are some ways to convert string to number in javascript.

The best way:

var num = +str;

It's simple enough and work with both int and float
num will be NaN if the str cannot be parsed to a valid number

You also can:

var num = Number(str); //without new. work with both int and float

or

var num = parseInt(str,10); //for integer number
var num = parseFloat(str); //for float number

DO NOT:

var num = new Number(str); //num will be an object. (typeof num == 'object') will be true.

Use parseInt only for special case, for example

var str = "ff";
var num = parseInt(str,16); //255

var str = "0xff";
var num = parseInt(str); //255
cuixiping
  • 24,167
  • 8
  • 82
  • 93
2
var num = Number(str);
Amarghosh
  • 58,710
  • 11
  • 92
  • 121
0

var f = parseFloat(str);

Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
lincolnk
  • 11,218
  • 4
  • 40
  • 61