For a JavaScript string that begins with an integer, use parseInt(value, 10); the second argument specifies base 10. If the whole string must represent a number, use Number(value) instead, because it rejects trailing text rather than silently ignoring it.
The basic string-to-integer function
JavaScript has no separate built-in function named stringToInt. The usual choice is the global parseInt() function, which reads an integer from the start of a value and returns a JavaScript number. For example, parseInt('42', 10) returns 42.
Pass the input as the first argument and the radix, or number base, as the second. For ordinary decimal values, specifying 10 makes the intent clear and avoids relying on defaults:
const quantity = parseInt('42', 10);
The result is still a JavaScript Number, not a special integer type. JavaScript uses the same Number type for whole numbers and decimal fractions, so a value such as 42 can be an integer-valued Number without having a different underlying type.
The key question is what to do with imperfect input. If '42 items' should produce 42, parseInt() may suit the task. If that input should be considered invalid, use a stricter conversion and validate the result.
How parseInt reads a value
parseInt() converts its first argument to a string, skips leading whitespace, reads an optional plus or minus sign, and then reads digits that are valid for the selected radix. It stops at the first character that cannot be part of the integer. It does not require the entire input to be consumed.
parseInt('27', 10)returns27.parseInt('27px', 10)also returns27, because parsing stops at thep.parseInt('8.9', 10)returns8; it truncates the parse at the decimal point rather than rounding.parseInt('text 27', 10)returnsNaN, because the first non-whitespace character is not a valid digit or sign.
This stopping behavior is useful when a value intentionally has a numeric prefix, but it can hide bad data when the input is supposed to be an exact integer. For instance, converting a form field containing '15abc' to 15 may make an invalid entry look acceptable. Choose the function based on whether trailing characters are allowed by the rules of your application.
parseInt() does not preserve fractional information. If the input is '8.9', the result is not a rounded value; it is the integer portion read before parsing stops. To convert decimal text, use Number() or parseFloat(), depending on whether trailing characters should be accepted.
Why the radix matters
The radix tells parseInt() which base to use. Decimal, the base used for everyday numbers, is radix 10. Hexadecimal is base 16, binary is base 2, and the function accepts radices from 2 through 36. In bases above 10, letters provide additional digit values; for example, A represents 10 in hexadecimal.
For decimal input, use parseInt(text, 10). This is clearer than leaving out the radix and makes the intended interpretation explicit. If the input is known to be hexadecimal, use parseInt(text, 16). For example, parseInt('ff', 16) returns 255.
When the radix is omitted or set to 0, modern JavaScript treats ordinary numbers as decimal and recognizes a leading 0x or 0X as a hexadecimal prefix. Older JavaScript environments had inconsistent legacy behavior around leading zeroes, which is one reason explicitly passing a radix became standard advice. A radix of 10 is not appropriate for every input: use the base that matches the data format.
Choosing between parseInt, Number, and unary plus
Number() converts a value using JavaScript’s numeric conversion rules. Unlike parseInt(), it generally requires the whole non-whitespace string to form a valid numeric value. That makes it a better fit when trailing text should cause rejection:
Number('27')returns27.Number('27px')returnsNaN.Number('8.9')returns8.9.Number('')andNumber(' ')return0, a behavior that can surprise when empty input is meant to be invalid.
The unary plus operator performs the same kind of numeric conversion for ordinary values: +'27' produces 27, and +'27px' produces NaN. It is concise, but Number(value) is often easier for readers to recognize. Neither one automatically guarantees an integer; check the result when fractions are not acceptable.
Use parseInt() when you deliberately want to read an integer prefix or interpret digits in a specified base. Use Number() when the complete value should be numeric, including possible decimals. Use unary plus when a compact conversion is helpful and the surrounding code makes its purpose obvious. These choices are not interchangeable: parseInt('4.7', 10) gives 4, while Number('4.7') gives 4.7.
Common examples and edge cases
Scientific notation is an especially useful example of the difference. Number('1e3') returns 1000, because the complete string is valid numeric notation. parseInt('1e3', 10) returns 1, because e is not a decimal digit and parsing stops there. If an API or form accepts exponent notation, do not use parseInt() as its general number converter.
Hexadecimal strings also depend on the chosen function. parseInt('0x10', 16) returns 16. Number('0x10') also returns 16, because Number conversion recognizes hexadecimal notation. But a value such as '12px' still distinguishes the functions: parseInt('12px', 10) gives 12, while Number('12px') gives NaN.
Whitespace around a valid number is accepted by both approaches: parseInt(' 12 ', 10) returns 12, and Number(' 12 ') does too. Empty text is different: parseInt('', 10) returns NaN, but Number('') returns 0. If empty input has a special meaning in your program, check for it before conversion instead of assuming the conversion will reject it.
Commas used as thousands separators are not automatically handled as grouping marks. Number('1,200') returns NaN, and parseInt('1,200', 10) returns 1, stopping at the comma. Do not remove punctuation indiscriminately: first establish the input format and locale, then parse according to those rules.
Handling NaN and validating integer input
A failed numeric conversion usually returns NaN, short for Not-a-Number. Despite its name, NaN has the JavaScript type number. A direct comparison such as result === NaN never detects it, because NaN is unequal to every value, including itself. Use Number.isNaN(result) to check for this specific failure value.
For a general conversion that must produce a finite value, use Number.isFinite(result). To check that a number has no fractional part, use Number.isInteger(result). For integers that must be represented exactly, prefer Number.isSafeInteger(result). For example, with const result = Number('42'), the result is 42, and both Number.isInteger(result) and Number.isSafeInteger(result) return true.
A safe integer is within JavaScript’s exactly representable integer range, from -(2^53 - 1) through 2^53 - 1. Above that range, distinct whole-number values may map to the same Number. Converting a long digit string can therefore yield a numeric result that looks plausible but has lost precision. If exact large integers matter, consider BigInt rather than Number, and do not treat parseInt() as an exact large-integer parser.
If the requirement is a whole decimal integer and trailing characters are forbidden, validate the text before converting it. For example, this helper accepts an optional sign and one or more ASCII decimal digits, trims surrounding whitespace, and returns NaN for other input or an unsafe result:
function parseWholeDecimal(value) {
const text = String(value).trim();
if (!/^[+-]?[0-9]+$/.test(text)) return NaN;
const number = Number(text);
return Number.isSafeInteger(number) ? number : NaN;
}
This is only one possible input policy. If callers can pass values other than strings, decide explicitly whether values such as null or booleans should be accepted; converting them to strings first makes them fail this particular digit pattern. Validation should express the format your application expects, not merely make a conversion function return some number.
When to use parseFloat or BigInt
parseFloat() reads a decimal number, including a fractional part, from the beginning of a string. Like parseInt(), it can stop at trailing text: parseFloat('3.5kg') returns 3.5. It is useful for intentionally permissive prefix parsing, but it is not a strict validator. For a complete decimal value, use Number() and check that the result is finite if infinities are not allowed.
BigInt() is an alternative for integers outside the safe Number range when exact integer arithmetic is required. For example, BigInt('9007199254740993') can represent that decimal integer exactly. The input must be a valid integer representation; a decimal fraction such as '3.5' cannot be converted to a BigInt. BigInt and Number values also cannot be mixed freely in arithmetic expressions, so the choice affects later calculations as well as parsing.
Use Number for ordinary counts and values within its safe integer range. Choose BigInt only when the application needs exact larger integers and can keep the relevant calculations in BigInt form. For currency, identifiers, or other data where formatting and exactness have special requirements, the right representation depends on the application’s rules; parsing alone cannot decide those rules for you.
Frequently Asked Questions
What is the JavaScript function to convert a string to an int?
Use parseInt(string, 10) for a decimal integer. If the entire string must be a valid number, use Number(string) and check that the result is an integer.
Why should I pass 10 to parseInt?
The second argument is the radix, or base. Passing 10 clearly requests decimal interpretation and avoids depending on default radix behavior.
Does parseInt round a decimal string?
No. parseInt('6.8', 10) returns 6 because it stops at the decimal point. Use Math.round() if rounding is specifically what your rules require.
How do I check whether parseInt failed?
Store its result and check Number.isNaN(result). Do not compare the result to NaN with an equality operator.
Should I use parseInt or Number?
Use parseInt() when accepting an integer prefix is intentional. Use Number() when trailing characters should invalidate the input or when decimal values may be valid, then apply the checks your application needs.
Related
- Split in SQL Server: STRING_SPLIT and Practical Examples
- SQL Split Syntax: Split Strings by Delimiter
- Split in SQL: Practical Methods for Common Databases
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Do a Label Mail Merge in Word: Step-by-Step GuideTo do a label mail merge in Word, open a blank document, choose Mailings > Start Mail Merge…
- How to Insert a First-Line Indent in Microsoft WordTo insert a first-line indent in Word, click in a paragraph or select several paragraphs, then open Home…
- Badge Inventory Spreadsheet: Setup and TrackingA badge inventory spreadsheet is a workbook for recording the badges your organization owns, where they are, and…
- How to Quit Excel When It’s Not RespondingIf Excel says “Not Responding” and will not close, first give it a short chance to finish working;…
- Excel Remove Duplicates: Steps and Safer OptionsTo remove duplicates in Excel for Microsoft 365 on Windows, select your data, then choose Data > Remove…
- How to Make a Booklet in Word 2016: Setup and PrintTo make a booklet in Word 2016, open Layout > Margins > Custom Margins, set Multiple pages to…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.