0
0
JavascriptHow-ToBeginner · 2 min read

JavaScript How to Convert String to Number Easily

In JavaScript, convert a string to a number using Number('123'), parseInt('123'), or parseFloat('123.45') depending on the number type you want.
📋

Examples

Input'123'
Output123
Input'45.67'
Output45.67
Input'abc'
OutputNaN
🧠

How to Think About It

To convert a string to a number, think about what kind of number you want: whole number or decimal. Use Number() for general conversion, parseInt() for whole numbers, and parseFloat() for decimals. If the string can't be converted, the result will be NaN.
📐

Algorithm

1
Get the input string.
2
Choose the conversion method based on the number type needed.
3
Apply the conversion method to the string.
4
Return the converted number or NaN if conversion fails.
💻

Code

javascript
const str1 = '123';
const str2 = '45.67';
const str3 = 'abc';

console.log(Number(str1));    // 123
console.log(parseInt(str2));  // 45
console.log(parseFloat(str2)); // 45.67
console.log(Number(str3));    // NaN
Output
123 45 45.67 NaN
🔍

Dry Run

Let's trace converting '45.67' using parseInt and parseFloat.

1

Input string

'45.67'

2

Apply parseInt

parseInt('45.67') returns 45 (stops at decimal)

3

Apply parseFloat

parseFloat('45.67') returns 45.67 (keeps decimal)

MethodInputOutput
parseInt'45.67'45
parseFloat'45.67'45.67
💡

Why This Works

Step 1: Number() converts whole or decimal strings

Number() tries to convert the entire string to a number, returning NaN if it fails.

Step 2: parseInt() reads whole numbers only

parseInt() reads the string until it finds a non-digit, so it stops at decimals.

Step 3: parseFloat() reads decimals

parseFloat() reads the string including decimal points to convert to a floating-point number.

🔄

Alternative Approaches

Unary plus operator
javascript
const num = +'123';
console.log(num); // 123
Quick and concise, but less readable for beginners.
Using *1 multiplication
javascript
const num = '123' * 1;
console.log(num); // 123
Works by forcing numeric conversion, but less explicit.

Complexity: O(1) time, O(1) space

Time Complexity

Conversion methods run in constant time because they process the string once without loops.

Space Complexity

No extra memory is needed besides the output number, so space is constant.

Which Approach is Fastest?

All methods run in constant time; unary plus is fastest in practice but less clear.

ApproachTimeSpaceBest For
Number()O(1)O(1)General conversion of strings to numbers
parseInt()O(1)O(1)Extracting integers from strings
parseFloat()O(1)O(1)Extracting decimal numbers
Unary plus (+)O(1)O(1)Quick conversion with concise syntax
💡
Use Number() for general conversion and parseInt() or parseFloat() when you need specific integer or decimal parsing.
⚠️
Trying to convert non-numeric strings without checking can result in NaN, which can cause bugs if not handled.