20
var str = '0.25';

How to convert the above to 0.25?

3
  • parseInt is blazing fast, but if you need decimals, you should go with parseFloat: jsbench.me/pokty2hchw/1 Commented Sep 24, 2021 at 8:03
  • '0.25'*1 is about 98% faster than parseFloat() jsbench.me/bflb5lcqpw/1 Commented Dec 1, 2022 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: jsbench.me/c8ldyhrth3/1 Commented Feb 10, 2023 at 12:18

4 Answers 4

43

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Also, for integers (only), there's ~~str and str | 0
Without knowing the implications and side effects of each of these, I'd opt for Number(str) as it's the most readable & interpretable code.
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

Comments

2
var num = Number(str);

Comments

0

var f = parseFloat(str);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.