Cost Check Now
Programming·JavaScript

How to convert a string to a number in JavaScript (2026)

Verified from sources

Quick Answer

In JavaScript, the safest everyday way to convert a string to a number is usually Number(str) when you want the whole string to be a valid number, or parseInt(str, 10) / parseFloat(str) when you want to read a number from the start of a string. Always check the result with Number.isNaN() if the input might be invalid. The best method depends on whether you want strict conversion, decimal support, or partial parsing.

Overview

Converting a string to a number in JavaScript sounds simple, but the right method depends on your input and how strict you need to be. Some methods convert only if the entire string is numeric, while others will pull a number from the beginning of a string and ignore the rest. That difference matters when you are handling form fields, query parameters, CSV data, API responses, or user-entered values. For most code, start by deciding whether invalid input should fail completely or be partially accepted. Number() is strict: if the string is not a valid numeric value, it returns NaN. parseInt() and parseFloat() are more forgiving: they read what they can from the start of the string, which can be useful but can also hide bad data. Unary plus (+str) behaves similarly to Number() and is concise, though sometimes less readable for beginners. Good practice is to trim whitespace if needed, choose the conversion method deliberately, and then validate the result before using it in calculations or comparisons. This avoids subtle bugs such as accidental string concatenation, unexpected NaN values, or accepting malformed input without realising it.

Who this is for

JavaScript beginners, front-end developers handling form input, back-end developers processing text data, and anyone debugging why a numeric value is still being treated as a string.

What you’ll need

  • A JavaScript environment such as a browser console, Node.js, or a code editor
  • Basic understanding of JavaScript variables and functions
  • A string value you want to convert

Before you start

Check what kind of input you actually have: whole numbers, decimals, values with spaces, empty strings, or strings that may contain text. Also decide whether you want strict validation or whether reading a leading numeric part is acceptable.

Step-by-step

  1. 1

    Inspect the input string

    Look at the exact value you are converting, including spaces, decimal points, signs, and any non-numeric characters. If the value comes from a form or API, confirm whether it is always a string and whether empty input is possible.

    Why: Different conversion methods behave differently with blanks, whitespace, decimals, and trailing text. Knowing the input shape prevents choosing a method that silently accepts bad data.

  2. 2

    Use Number() for strict whole-string conversion

    If the entire string should represent a valid number, use Number(str). Example: Number("42") returns a number, and Number("42px") returns NaN.

    Why: This is usually the clearest strict conversion method. It helps catch invalid input instead of partially converting it and hiding a data problem.

  3. 3

    Use parseInt() for integers and specify base 10

    If you need an integer from the start of the string, use parseInt(str, 10). Example: parseInt("42", 10) gives an integer, and parseInt("42px", 10) reads the leading number.

    Why: Supplying the radix makes your intent explicit and avoids ambiguity. This matters when reading user or external input where consistency is important.

  4. 4

    Use parseFloat() when decimals are expected

    If the input may contain a decimal number at the start, use parseFloat(str). Example: parseFloat("3.14") returns a decimal number, and parseFloat("3.14m") reads the leading numeric part.

    Why: parseFloat() is useful for decimal input, but it is still permissive, so you should only use it when partial parsing is genuinely acceptable.

  5. 5

    Use unary plus only when brevity will not hurt readability

    You can write +str as a short way to convert a string to a number. It behaves much like Number(str). Example: +"25" converts to a number.

    Why: This is concise and common in experienced JavaScript code, but it can be less obvious to readers who are not familiar with the pattern.

  6. 6

    Validate the result before using it

    After conversion, check the result with Number.isNaN(value) if invalid input is possible. If needed, also check that the result is finite with Number.isFinite(value).

    Why: NaN can silently break calculations and comparisons. Validation makes your code safer when working with user input, imported data, or optional fields.

  7. 7

    Handle empty or malformed input explicitly

    Decide what your code should do with values such as an empty string, whitespace-only input, or mixed text. You may want to trim the string first, reject it, or provide a fallback value.

    Why: Leaving these cases undefined can lead to inconsistent results and hard-to-find bugs, especially in forms and data pipelines.

Why this works

JavaScript provides several built-in conversion paths. Number() and unary plus attempt to convert the entire value using JavaScript's numeric conversion rules, while parseInt() and parseFloat() parse numeric characters from the start of a string. Choosing the right one lets you control how strict or forgiving the conversion should be.

Common mistakes to avoid

  • Using parseInt() without the radix argument when you really mean base 10
  • Using parseInt() on decimal values and then wondering why the fractional part disappears
  • Assuming parseFloat() or parseInt() will reject strings with trailing text
  • Forgetting to check for NaN before doing arithmetic
  • Using a value from a form field as if it were already a number
  • Accidentally concatenating strings instead of adding numbers

Troubleshooting

The result is NaN

Log the original string, trim it if appropriate, and check whether it contains invalid characters or is empty. Use Number.isNaN() to detect this case reliably.

The value is being joined as text instead of added numerically

Convert both operands before adding, for example with Number() or unary plus, so JavaScript performs arithmetic rather than string concatenation.

Decimal input is being cut off

Do not use parseInt() for decimal values. Use Number() for strict conversion or parseFloat() if partial parsing is acceptable.

A string like "42px" is being accepted when it should fail

Use Number() instead of parseInt() or parseFloat(), because Number() rejects extra non-numeric characters.

Blank input gives an unexpected result

Handle empty strings explicitly before conversion. Decide whether blank means invalid, zero, or 'no value' in your application.

Compare your options

Number(str)

Best for: Strict conversion where the whole string must be numeric

Pros: Clear intent, handles integers and decimals, rejects trailing text

Cons: Returns NaN for malformed input, which must be checked

parseInt(str, 10)

Best for: Reading an integer from the start of a string

Pros: Useful when input may contain a unit or suffix, explicit radix improves clarity

Cons: Drops decimal part, accepts partial input, can hide invalid trailing text

parseFloat(str)

Best for: Reading a decimal number from the start of a string

Pros: Works with decimal input, useful for permissive parsing

Cons: Accepts trailing text, not suitable when strict validation is required

Unary plus (+str)

Best for: Short strict conversion in concise code

Pros: Very brief, similar behaviour to Number()

Cons: Less readable for some developers

Alternatives

  • Use HTML input types and built-in validation to reduce bad input before it reaches your JavaScript
  • Use a schema validation library in larger applications to validate and convert incoming data centrally
  • Keep values as strings until validation is complete if you need to preserve the original input for error reporting

Pro tips

  • Prefer Number() when you want invalid input to fail clearly.
  • Always pass 10 as the second argument to parseInt() unless you have a deliberate reason to use another base.
  • Use Number.isNaN() rather than the global isNaN() when checking the conversion result.
  • Trim user input if leading or trailing spaces are common in your application.
  • Write tests for edge cases such as empty strings, decimals, negative values, and strings with units.

Safety notes

  • Validate and sanitise user input before using converted values in application logic, pricing, limits, or security-sensitive code.
  • Do not assume a successful conversion means the value is sensible; check ranges and business rules separately.
  • Be especially careful when converting external data from forms, URLs, CSV files, or APIs, because permissive parsing can hide data quality issues.

What this guide does not cover: This guide covers standard JavaScript string-to-number conversion methods, but it does not go deeply into locale-specific number formats, BigInt conversion, custom parsing rules, or framework-specific form handling.

Cost considerations

There is no direct cost to using JavaScript's built-in conversion methods, but poor input handling can increase debugging time and maintenance effort in production systems.

Frequently asked questions

What is the difference between Number() and parseInt()?+

Number() expects the whole string to be a valid numeric value, while parseInt() reads an integer from the start of the string and stops when it reaches a non-integer character.

Should I use parseFloat() for decimal numbers?+

Use parseFloat() only if you are happy to accept a decimal number from the start of a string even if extra text follows. If you want strict validation, use Number() instead.

How do I check whether conversion failed?+

Store the result and test it with Number.isNaN(result). If you also need to reject Infinity or -Infinity, use Number.isFinite(result).

Why does adding two values from form fields sometimes produce the wrong result?+

Form field values are usually strings. If you add them without conversion, JavaScript may concatenate them as text instead of performing numeric addition.

Is unary plus a good idea?+

Yes, when your team finds it readable. It is concise and behaves similarly to Number(), but Number() is often clearer for beginners and shared codebases.

Sources & references

Guidance on this page is traced to documented sources. Last checked 24 September 2026.

These core JavaScript conversion methods are long-established and change very slowly.

Related guides

Legal Disclaimer: The information provided on Cost Check Now is for general informational and educational purposes only. It does not constitute financial, legal, professional, or any other form of advice. Cost Check Now makes no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability, or availability of any information, products, services, or related graphics contained on this website. Any reliance you place on such information is strictly at your own risk. In no event will Cost Check Now, its owners, operators, contributors, or affiliates be liable for any loss or damage including without limitation, indirect or consequential loss or damage, or any loss or damage whatsoever arising from loss of data or profits arising out of, or in connection with, the use of this website. Always seek independent professional advice before making financial or purchasing decisions.