VIEW THIS AS

Auto mode follows the Route Engine until you choose a viewpoint.

YOU ARE HERE

ROUTE CHECK

CONNECTED TO

WHAT NEXT

Use the canonical route for this room, or HELP if you are unsure.

The Gold Standard of Websites | Separating parseInt Prefix Parsing from Complete String Number Conversion

A booking form receives the text “18 seats”. One helper reports 18; another reports NaN. Both can be following their defined rules. The important question is whether the website promised to accept a numeric prefix, a complete numeric string, or a particular quantity format.

The short answer is that parseInt reads an initial run of digits in its chosen radix after its allowed leading processing. Number, when given a string, applies a numeric grammar to the complete supplied string, including its permitted whitespace. Neither operation by itself establishes a website's business rule.

This guide uses original fictional booking and archive examples. It concentrates on string inputs, exact intermediate values and explicit acceptance policies. Conversion of arbitrary objects, browser number controls and server parsers have additional contracts; they should not be silently treated as the same operation.

This specialist guide belongs to the Websites root. It also connects to The Gold Standard of Education | Learning That Transfers into Life and the How X Works hub. The worked cases are original teaching examples; their numbers are stipulated so that the reasoning can be checked.

eduKateSG · Websites

Find your next learning step

Compare numeric prefix parsing with complete-string conversion. Preserve source spelling, choose a field grammar and check finite, safe, permitted quantities.

ROUTE 1 · CHAPTERS 1–3

Name the accepted text

Follow a prefix and compare it with the complete string grammar.

ROUTE 2 · CHAPTERS 4–6

Vary numeric notation

Work fractions, exponents, radix, blanks and nonfinite values.

ROUTE 3 · CHAPTERS 7–9

Preserve type and identity

Keep codes as text and trace callback arguments and numeric stringification.

ROUTE 4 · CHAPTERS 10–12

Define and test a policy

Build a bounded seat field, adapt a measurement field and check exact boundaries.

ROUTE 5 · CHAPTERS 13–14

Repair and report

Locate the missing acceptance step and preserve the intended meaning.

Full chapter contents · Websites subject guide

Chapter contents

Name the accepted text · Chapters 1–3

1. Name the question before choosing a converter

2. Work a decimal prefix one character at a time

3. Contrast the complete string grammar

Vary numeric notation · Chapters 4–6

4. Change decimal points and exponents independently

5. Treat the radix as part of the input contract

6. Keep blank, zero, failed conversion and infinity separate

Preserve type and identity · Chapters 7–9

7. Preserve written identifiers when quantity is the wrong meaning

8. Recognise the callback-argument trap

9. Avoid using text parsing as a numeric truncation shortcut

Define and test a policy · Chapters 10–12

10. Build a narrow seat-count policy deliberately

11. Transfer the policy to a different measurement task

12. Use boundary fixtures that expose lost distinctions

Repair and report · Chapters 13–14

13. Repair the first unsupported acceptance step

14. Report text, interpretation and accepted quantity separately

CHAPTER 1 OF 14 · Name the accepted text

1. Name the question before choosing a converter

Back to contents

Imagine a fictional workshop with a field asking for the number of seats. Its instruction says “Enter a whole number from 1 to 120”. The person enters "18 seats". A helper using parseInt with radix ten obtains 18. A helper using Number obtains NaN, the Number value used here to represent failed numeric interpretation.

The first helper found a usable decimal prefix. It did not certify that every character belonged to the promised seat-count format. The second helper did not find a valid complete numeric string. Its failure does not mean that humans cannot understand the phrase. It means that this particular conversion grammar does not accept it as a whole number representation.

parseInt("18 seats", 10); // 18
Number("18 seats");       // NaN

There are legitimate jobs for prefix parsing. A deliberately defined exercise might ask for the leading decimal count before a textual annotation. That job differs from accepting a field whose entire content must be a decimal seat count. Replacing one question with the other can produce a plausible number while weakening the actual requirement.

Write the field contract before examining the helper. Does the application accept surrounding whitespace? Leading zeros? A plus sign? Decimal points? Scientific notation? Empty text? A measurement unit? These decisions are not interchangeable merely because several inputs can eventually describe the same mathematical quantity.

Keep the original text while evaluating it. If only the converted number survives, the difference between "18", "018" and "18 seats" can disappear. The website may then be unable to explain which spelling it accepted or why a correction was requested.

The starting habit is simple: identify the input type, the accepted written form, the converted value and the permitted quantity. A converter answers one stage of that sequence. A complete field decision must connect all four without pretending that a successful numeric result settles every stage.

Contents · Next chapter

CHAPTER 2 OF 14 · Name the accepted text

2. Work a decimal prefix one character at a time

Back to contents

For a controlled decimal example, use " -27boxes" with an explicit radix of ten. The leading spaces are ignored under parseInt's rule. The minus sign supplies a negative sign. The digits two and seven form the initial decimal digit run. The letter b ends that run. The resulting Number is negative twenty-seven.

The suffix is not consumed as a unit name, checked against an approved vocabulary or returned as a separate field. It is simply outside the interpreted prefix. The returned number contains no marker saying that the remaining text existed. That absence of a suffix report is why a caller should not use the number alone as proof of full-string acceptance.

parseInt("  -27boxes", 10); // -27
parseInt("boxes27", 10);   // NaN
parseInt("27 31", 10);     // 27

In the second case, there is no initial decimal digit after the permitted leading processing. The parser does not search through the word until it finds 27. In the third case, the internal space stops the digit run; the later 31 does not become part of the result. Prefix parsing is neither arbitrary number extraction nor removal of every nondigit character.

Ask the learner to annotate the first unaccepted character. For the boxes example, mark b. For the two-number example, mark the internal space. Then compare the result with the field's promised grammar. This locates a meaningful boundary rather than teaching a slogan that parseInt “gets the number out”.

If the application really needs a count plus a suffix, define both parts. A parser returning structured count and unit information can preserve the text needed for a later decision. Merely taking a numeric prefix leaves the suffix unexamined, so it cannot establish that the source said boxes rather than an unexpected or mistyped label.

Contents · Previous chapter · Next chapter

CHAPTER 3 OF 14 · Name the accepted text

3. Contrast the complete string grammar

Back to contents

With a string argument, Number attempts conversion according to the complete string numeric grammar. Permitted surrounding whitespace can be present. Internal arbitrary text cannot simply be ignored. Therefore " 27 " becomes 27 while "27boxes" becomes NaN under this conversion.

“Complete” does not mean “only unadorned decimal digits”. The accepted grammar is broader than many quantity fields. It includes decimal notation with a fractional part or exponent, certain nondecimal integer prefixes, signed decimal forms and Infinity. It also assigns zero to empty or whitespace-only strings. Each of these can matter when Number is used as a proposed validator.

Number(" 27 ");    // 27
Number("2.7e1");   // 27
Number("");        // 0
Number("   ");     // 0

The first two inputs describe the same mathematical quantity through different accepted representations. A field that permits only ordinary decimal whole-number spelling can still reject the exponent form. A field that distinguishes missing information from a supplied zero must also handle the empty-string rule deliberately.

This is why replacing parseInt with Number is not a complete acceptance policy. It changes the conversion boundary in a useful way for some tasks, but it does not decide whether blank text is missing, whether Infinity is allowed, whether leading zeros carry identity or whether a fractional result is permitted.

For the seat-count exercise, separate written-form checking from numeric checking. The text might first be trimmed under a declared policy, then tested as decimal digits, then converted, then checked against the allowed range. Another field can choose another grammar, but its sequence should be equally explicit.

A precise explanation therefore says that Number rejected the trailing word under its complete string grammar. It should not say that Number proves the entry is a valid booking quantity whenever conversion succeeds. Successful conversion and accepted use are distinct conclusions, supported by different checks.

Contents · Previous chapter · Next chapter

CHAPTER 4 OF 14 · Vary numeric notation

4. Change decimal points and exponents independently

Back to contents

Use "18.75" to distinguish integer-prefix parsing from whole-string decimal conversion. With radix ten, parseInt reads the digits 18 and stops at the decimal point. Number converts the complete decimal representation to eighteen and three quarters. Neither operation rounds the quantity to the nearest seat.

The difference becomes more striking with "18e2". Decimal prefix parsing stops at e and returns 18. Whole-string conversion interprets the exponent notation and returns 1800. A helper that appears satisfactory on ordinary integers can therefore produce a quantity one hundred times smaller when the spelling changes.

parseInt("18.75", 10); // 18
Number("18.75");       // 18.75
parseInt("18e2", 10);  // 18
Number("18e2");        // 1800

In a field requiring a whole number, the correct response to a fractional spelling depends on the field policy. It might reject the entry and retain it for correction. It should not silently discard a fractional part merely because the helper returns an integer. Truncation is a quantity transformation, while rejecting an unsuitable written form is an acceptance decision.

For already numeric values, an explicit numeric truncation operation has its own contract. It does not need to stringify a number and parse an initial digit sequence. For negative quantities, also distinguish truncation towards zero from rounding down towards negative infinity. Those operations can agree on positive examples and disagree on negative ones.

This lesson's booking field needs no rounding rule because it accepts decimal whole-number text only. Stating that narrow requirement prevents the example from smuggling in an unexplained policy. The rejected fractional text remains available so the person can decide whether they intended 18 or 19 rather than having the website choose for them.

For transfer practice, change the example to an archive measurement field that genuinely accepts scientific notation. Number's exponent interpretation can then be useful, followed by checks for finiteness, units and range. The same conversion result has to be judged against the new field's purpose rather than the old booking rule.

Contents · Previous chapter · Next chapter

CHAPTER 5 OF 14 · Vary numeric notation

5. Treat the radix as part of the input contract

Back to contents

A radix determines which digits are available and what place values they represent. Decimal uses ten, binary uses two and hexadecimal uses sixteen. Passing an explicit radix to parseInt makes that choice visible, but it does not require the parser to consume the complete string.

For hexadecimal "2A", radix sixteen gives forty-two. In decimal, the same text has the valid initial digit two followed by an unaccepted letter A, so the result is two. Both calls can return numbers while describing different interpretations. An absent error does not establish that the intended radix was used.

parseInt("2A", 16); // 42
parseInt("2A", 10); // 2
parseInt("102", 2); // 2: binary prefix "10"

The binary example is worth working slowly. The first digit one contributes two in its final two-digit binary prefix. The following zero contributes zero. The digit two is not a binary digit, so it ends the interpreted prefix. The returned value two does not certify that 102 was valid binary text.

Under parseInt's omitted-or-zero-radix rule, a leading hexadecimal prefix can select sixteen; otherwise the default is decimal. An explicit radix of sixteen also permits the hexadecimal prefix. These rules differ from Number's complete string grammar, which can recognise supported nondecimal integer notation as a whole.

Do not teach a broad rule that every leading zero selects octal in modern parseInt. That would misdescribe the current ordinary contract. Equally, do not assume that every prefix Number recognises is automatically interpreted in the same way by decimal parseInt.

For real technical input, document whether the user supplies a prefix, chooses a radix separately or enters a fixed-format identifier. If a field requires complete hexadecimal text, check that written form explicitly before conversion. A numeric value alone cannot reveal that a trailing invalid digit or letter was ignored under the prefix parser's rules.

Contents · Previous chapter · Next chapter

CHAPTER 6 OF 14 · Vary numeric notation

6. Keep blank, zero, failed conversion and infinity separate

Back to contents

A person leaving a quantity field blank has not necessarily supplied zero. Number's string conversion can map both empty text and whitespace-only text to positive zero. If the application checks only whether the result is a number, missing information can become indistinguishable from a deliberate zero.

parseInt of empty or whitespace-only text instead gives NaN because there is no initial digit run. This difference can make one helper seem more suitable for detecting missing entries. It is still clearer to check the declared text policy directly rather than relying on an incidental difference between converters.

NaN needs a suitable observation. It does not compare equal to itself, so testing equality against NaN is not a useful conversion-failure check. Number.isNaN examines whether the value is that Number value without first coercing a new string argument. Use the converted result, not an unconverted field string, when applying that test.

Number.isNaN(Number("18 seats")); // true
Number.isNaN("18 seats");         // false: still a string
Number.isFinite(Number("Infinity")); // false

Infinity provides another boundary. It is accepted by the string numeric grammar, but it is not a finite seat count. A finite-number check answers a different question from a NaN check. A range check answers another question again. The booking exercise eventually needs a finite whole number within its allowed range, and its written form must satisfy the declared decimal policy.

Zero itself can require a decision. Our booking contract excludes it because at least one seat is required. Another form might allow zero as a meaningful quantity while still rejecting blank text. That difference should be represented in the checks and error message.

Avoid truthiness as a substitute for these distinctions. A zero result is falsy; an invalid text string can be truthy before conversion. A condition that merely asks whether something is truthy can collapse type, presence and quantity into one ambiguous branch. Name the intended question and use the observation that actually answers it.

Contents · Previous chapter · Next chapter

CHAPTER 7 OF 14 · Preserve type and identity

7. Preserve written identifiers when quantity is the wrong meaning

Back to contents

Suppose the archive asks for an item code rather than a quantity. Its code is "0018". Converting it to a Number produces 18 and removes the written leading zeros from the retained value. That may be mathematically harmless for a count but unacceptable for an identifier.

The code could also contain more digits than an ordinary Number can represent exactly as an integer. Both successful prefix parsing and complete string conversion return Number values in these examples. Neither guarantees exact preservation of every long decimal identifier. A valid-looking output can therefore hide loss of identity even when every original character was a digit.

Use a deliberately small identity fixture first. Store the source code "0018" as text, compare it with "18", and ask whether the catalogue contract treats them as the same identifier. Do not answer by converting both and observing equality; that would assume the very equivalence under investigation.

If a field is genuinely a large integer quantity, choose a representation appropriate to its required precision. BigInt has a different type and grammar context, with separate interoperability decisions. It should not be introduced merely because a label happens to contain many digits. Often the correct representation for a code is simply a string.

Number.isSafeInteger helps identify whether a Number is an integer within the range where integer values have the required safe representation property. It cannot reconstruct digits already lost during a previous conversion. A check after loss may reject a value, but it does not recover the original source.

The practical decision begins with meaning: arithmetic quantity, formatted code, measurement or source text for review. Keep that meaning through storage and display. A website that preserves an archive code as text can still derive a separate numeric quantity when a documented use actually needs one. It should not replace the authoritative identifier with that derived representation by default.

Contents · Previous chapter · Next chapter

CHAPTER 8 OF 14 · Preserve type and identity

8. Recognise the callback-argument trap

Back to contents

Passing parseInt directly as an array mapping callback is a compact way to create an unexpected radix. Array mapping supplies a value, its index and the source array. parseInt uses its second argument as the radix. The callback's index therefore becomes part of numeric interpretation rather than harmless extra information.

Consider the three strings "10", "11" and "12". At index zero, a radix of zero selects the ordinary default and the result is ten. At index one, radix one is outside the supported range and the result is NaN. At index two, radix two reads the binary prefix one from 12 and stops at the invalid digit two, producing one.

["10", "11", "12"].map(parseInt);
// [10, NaN, 1]
["10", "11", "12"].map(text => parseInt(text, 10));
// [10, 11, 12]

The second expression fixes the radix intentionally. It does not make prefix parsing a complete-field validator. A fourth value such as "13chairs" would still produce thirteen under that helper. Correct callback adaptation and correct field grammar remain separate responsibilities.

This is a useful connection to the existing Array.from mapping lesson. A callback signature belongs to the calling operation. A function that works when called with one manually chosen argument can behave differently when another API supplies extra arguments with meanings the function already recognises.

Do not rely on JSON serialization alone to inspect the failing result. Some values, including NaN in an ordinary JSON array serialization, acquire a different representation. A diagnostic should assert numeric NaN directly and retain the original strings and indices. Otherwise a displayed null can send the investigation towards a missing-record theory rather than the actual radix mismatch.

For repair practice, ask the learner to predict each invocation before evaluating the array. The explanation should include the supplied index and selected radix, not merely memorise that mapping parseInt is “bad”. That reasoning transfers to other callback APIs with different extra arguments.

Contents · Previous chapter · Next chapter

CHAPTER 9 OF 14 · Preserve type and identity

9. Avoid using text parsing as a numeric truncation shortcut

Back to contents

parseInt first converts its input to a string. Our main lesson deliberately supplies strings, so that step has been straightforward. When a caller supplies an existing Number, its written representation can become part of the result in a way that has little to do with the intended arithmetic transformation.

A sufficiently large Number can stringify in exponent notation. A very small positive Number can do the same. Decimal prefix parsing then stops at the exponent marker. For a controlled example, parsing the Number one times ten to the twenty-first power can return one from its initial digit, rather than preserve the enormous integer quantity.

parseInt(1e21, 10); // 1
Math.trunc(1e21);   // 1e21
parseInt(1e-7, 10); // 1
Math.trunc(1e-7);   // 0

The third expression is a particularly clear counterexample to describing parseInt as universal truncation. The numeric value is less than one, but its converted source spelling begins with one. The prefix parser follows that spelling. It is doing a text job on an intermediate representation, not simply removing the mathematical fractional part.

For an existing Number that really needs truncation, use a numeric operation with a documented rounding direction and appropriate handling of nonfinite values. For field text that requires validation, retain the text and check its form. Those are different starting types and should not be merged into one vague “make it an integer” helper.

Arbitrary objects add another conversion question. parseInt and Number can obtain primitive values through different conversion paths, potentially invoking user-defined behaviour. This guide does not offer a universal object-conversion wrapper. A field boundary can require strings explicitly, making its intended grammar and checks much easier to state.

Record the original type in a failing test. A displayed value of 1000000000000000000000 may conceal that a Number was already present before parsing. Comparing it with a string fixture of literal decimal digits is useful only when the changed input type is acknowledged.

Contents · Previous chapter · Next chapter

CHAPTER 10 OF 14 · Define and test a policy

10. Build a narrow seat-count policy deliberately

Back to contents

Return to the workshop's stated contract. The field accepts surrounding whitespace, then one or more ASCII decimal digits representing a whole number from one to one hundred and twenty. Under this exercise, leading zeros are permitted as quantity spelling, but the original text is retained for feedback. Units, signs, decimal points and exponents are excluded.

A small helper can implement that exact sequence. It first rejects nonstring input. It trims the permitted surrounding whitespace. It checks the remaining text as decimal digits, converts it, and applies the safe-integer and range conditions. The returned record keeps acceptance distinct from the quantity.

function readSeats(raw) {
  if (typeof raw !== "string") return { ok: false, reason: "type" };
  const text = raw.trim();
  if (!/^[0-9]+$/u.test(text)) return { ok: false, reason: "format" };
  const value = Number(text);
  if (!Number.isSafeInteger(value) || value < 1 || value > 120) {
    return { ok: false, reason: "range" };
  }
  return { ok: true, value };
}

This is an original teaching policy, not a claim that every booking website should accept exactly these forms. A different product can permit a plus sign or reject leading zeros, provided it declares and checks that rule. The helper is useful because its scope is explicit enough to challenge.

Notice that the decimal pattern runs after trimming. An empty result fails the pattern, so Number's blank-to-zero rule never supplies the application's missing-value policy. A text such as 18 seats also fails before conversion. The range stage is reserved for well-formed decimal quantities outside the allowed interval.

For a real interface, translate those internal reasons into useful messages tied to the field, preserve the person's entry, and repeat authoritative checks at the appropriate service boundary. A classroom helper does not establish that a deployed client and server share the policy. That wider claim needs evidence from the actual journey, version and accepted storage result.

Contents · Previous chapter · Next chapter

CHAPTER 11 OF 14 · Define and test a policy

11. Transfer the policy to a different measurement task

Back to contents

The archive now has a fictional measurement field accepting a finite decimal quantity in scientific notation. Its accepted range is zero to two thousand inclusive, and an empty entry means “not supplied”. This task differs from a whole-number seat count in written form, quantity type and missing-value meaning.

Before writing a helper, predict several inputs. The string "1.8e2" describes one hundred and eighty under Number's grammar and can satisfy the stated numeric range. The string "1.8e2mm" is not a complete numeric string and should not be accepted by merely taking a prefix. The string "Infinity" converts but fails finiteness. Blank text should follow the missing-value branch before conversion.

This changed context shows why the earlier decimal-digits pattern is not a universal solution. Reusing it would reject the scientific notation this field intentionally allows. Conversely, simply copying the measurement conversion into the seat field would permit spellings the seat contract intentionally excludes.

The unit also needs a clear home. If the interface supplies millimetres as a fixed documented unit, the numeric field can remain a quantity field. If users must enter a written unit, the accepted grammar and parser should identify it explicitly. A prefix parser that discards the suffix cannot distinguish millimetres from a mistyped or incompatible unit.

Now try an identifier task again: the archive code "0180" is not automatically the same as "180". The measurement field can treat their derived quantities alike while the identifier field preserves their distinct written identities. The same digits participate in different contracts.

An independent learner should therefore explain both what changed and what remained. The need to preserve input and inspect complete meaning remains. The accepted notation, numeric checks and result type can change. Transfer is successful when the learner adapts those decisions deliberately rather than exporting the original field's restrictions under a new label.

Locale-sensitive display introduces another changed condition. A person can read a comma as a decimal separator in one convention and as a grouping separator in another. Number conversion of a supplied string does not become a general locale-aware parser because the browser displays numbers in a selected locale. A formatter that produces a readable quantity and a parser that accepts user text perform different jobs. The measurement form should state or demonstrate its accepted notation and provide feedback consistent with the supported input method.

For a controlled comparison, take the text 1,800. Prefix parsing in decimal can stop at the comma and return one. Number rejects the complete comma-containing string under its ordinary grammar. Neither result decides whether the person intended eighteen hundred, one point eight, or an identifier containing a comma. Removing the comma would create an interpretation, not discover the user's intent. A product supporting localised entry should resolve that ambiguity through a declared locale and grammar rather than a silent punctuation cleanup.

The same discipline applies to currency symbols and units. A displayed price label can contain meaningful text around a number, while an editable quantity field can have a narrower contract. Extracting a prefix from a label is not evidence that the label's complete monetary or measurement meaning has been preserved. Keep a typed quantity, unit and source spelling in distinct fields when that is the system's design. Then the interface can format them for display without requiring a later reader to guess how a decorated string should be parsed back into its original meaning.

Contents · Previous chapter · Next chapter

CHAPTER 12 OF 14 · Define and test a policy

12. Use boundary fixtures that expose lost distinctions

Back to contents

Start a check set with an ordinary accepted seat count, its allowed surrounding whitespace, and exact endpoints one and one hundred and twenty. Then add zero and one hundred and twenty-one. These establish the quantity boundary after written-form acceptance. Include an empty string and whitespace-only string to protect the separate missing-or-format decision.

Add inputs designed to distinguish prefix parsing from complete conversion: a trailing unit, an internal space, a decimal fraction, exponent notation, a nondecimal prefix and a numeric separator-looking underscore. Predict both built-in conversion results and the application helper's acceptance result. They are different assertions.

For "1_000", decimal parseInt stops at the underscore and produces one, while Number rejects that complete string representation. Source-code numeric-literal syntax and string conversion syntax are not automatically identical. This fixture protects against copying an example from JavaScript code into a user-text grammar without checking the difference.

Test a sign-only string, a sign before digits, and a non-ASCII digit sequence if the declared field admits ASCII digits only. Rejecting that sequence under this narrow exercise is not a claim about its mathematical meaning or the quality of the language. If a product intends localised numeric input, it needs an explicit supported parsing and feedback policy.

Inspect NaN and negative zero using observations that preserve their distinctions. Object.is can distinguish negative zero from positive zero when that matters. JSON output alone may erase or change exceptional numeric representations, so it should not be the only oracle for a numeric conversion lesson.

Use fresh fixtures and retain the exact raw spelling. A test named “eighteen” is less informative than one recording whether it supplied 18, 018, 18.0 or 18e0. Each can produce the same quantity while challenging a different grammar rule. The best fixture names explain which boundary the input is meant to exercise.

Contents · Previous chapter · Next chapter

CHAPTER 13 OF 14 · Repair and report

13. Repair the first unsupported acceptance step

Back to contents

Suppose a booking helper currently uses decimal parseInt and accepts every result between one and one hundred and twenty. The observed failure is acceptance of 18 seats despite a whole-field decimal instruction. The missing step is examination of the complete accepted written form, not a different upper bound.

A focused repair can add the declared text policy and preserve the existing valid quantity range. Replay the failing trailing-unit input, an ordinary count, permitted whitespace and both endpoints. Then check a fraction and exponent so the repair does not merely recognise one unwanted word while leaving the same structural gap elsewhere.

Avoid silently deleting nondigits. Removing letters, signs and punctuation can turn several different inputs into the same digit sequence. A text such as one decimal digit, a point and another digit would acquire a different quantity. That transformation needs a genuine product requirement; it is not a neutral way to obtain “the number”.

Preserve submitted text during recovery. The person can correct the field without reconstructing other answers. A precise message such as asking for decimal digits within the stated range explains the next step better than calling every failure “not a number”, especially when a human can plainly read a quantity in the phrase.

If the actual requirement is prefix extraction, keep it and improve its report instead. A teaching helper can expose the consumed prefix and retained suffix through an explicitly defined parser. It should not describe that behaviour as complete validation. The repair follows the intended task, not a blanket preference for Number over parseInt.

After deployment, verify the actual receiving boundary and saved quantity under the system's authorised process. A corrected browser helper alone does not establish server acceptance or record integrity. Keep that implementation claim separate while giving a firm, testable answer about the conversion bug itself.

Contents · Previous chapter · Next chapter

CHAPTER 14 OF 14 · Repair and report

14. Report text, interpretation and accepted quantity separately

Back to contents

A useful conversion report records the original type and text, selected parser and radix, resulting numeric value, and the application's acceptance decision. If the parser stops early, record the first unconsumed character in the worked explanation. If conversion fails, preserve the raw spelling needed to understand why.

For the original booking input, the conclusion is precise. Decimal parseInt returns eighteen from the prefix of 18 seats. Number rejects the complete string as a numeric representation. The booking contract excludes trailing words, so acceptance requires an explicit whole-field rule; a returned eighteen alone does not establish compliance with that rule.

The same reporting structure explains why an exponent can change the result, why blank text can become zero and why a leading-zero archive code should remain text. It does not collapse these cases into one error category. Each begins with a different intended meaning or conversion condition.

For independent practice, ask a learner to design two fields: a count and an identifier. Give them identical digit-looking entries and require them to justify storage types, allowed spellings and recovery. Then add a scientific-notation measurement field. A strong answer reuses the reasoning while changing the policy appropriately.

Keep a compact set of exact fixtures beside the helper. Include at least one case that distinguishes prefix parsing from complete conversion and one case that distinguishes successful conversion from permitted use. These protect against future changes that appear simpler but erase a distinction the website promised to preserve.

The transferable habit is to resist stopping at a plausible number. Trace how text became that number, what information disappeared, and which rule authorises the resulting quantity. Once those stages are visible, a website can accept ordinary entries clearly, explain rejected forms accurately, and preserve identifiers and user intent without attributing more judgment to a converter than it actually provides.

Contents · Previous chapter · Return to Websites

Tracing Array.from Mapping Before Source Consumption Finishes

Tracing Array.from Mapping Before Source Consumption Finishes. A callback receives the arguments supplied by its calling operation; adapt its signature deliberately.

Tracing Default Array Sort Order Through Numbers, Undefined Values and Empty Slots

Tracing Default Array Sort Order Through Numbers, Undefined Values and Empty Slots. Numeric quantities and their string representations can produce different ordering behaviour too.

Tracing JSON Revivers from Child Values to the Final Root

Tracing JSON Revivers from Child Values to the Final Root. Parsing and later transformation cannot recover source information that was already discarded.

The Community Delivery Map Imported 400 Addresses but Dropped Leading Zeros from Postal Codes

The Community Delivery Map Imported 400 Addresses but Dropped Leading Zeros from Postal Codes. The full postal-code case develops source-preserved identifiers and downstream checks after leading zeros disappear.

Preserve field text before numeric interpretation. Captured separators, empty fields and a capped split result can change the sequence of texts reaching a converter. Establish those boundaries before accepting quantities.

Frequently asked questions

Does an explicit radix make parseInt validate the whole string?

No. It chooses digit interpretation. A later invalid character can still end a successfully parsed prefix.

Is Number a complete booking-field validator?

No. Its string grammar can accept forms such as blank-to-zero and Infinity that an application may need to exclude.

Does parseInt round a decimal quantity?

No. With decimal text it can stop at the point. That is different from an explicit numeric rounding policy.

Why does mapping parseInt produce surprising results?

The mapping callback's index is supplied as parseInt's radix argument. Adapt the callback explicitly when that is not intended.

Should a leading-zero code be converted to a number?

Only when the actual data contract defines it as a quantity. An identifier can require preserving its original written zeros.

Can JSON output verify every numeric distinction?

No. Use appropriate direct checks for NaN, negative zero, finiteness and exact expected values, while preserving raw source text.

Authoritative sources and further reading

ECMAScript: parseInt. Radix choice, sign handling and the initial accepted digit sequence.

ECMAScript: string numeric conversion. The complete string grammar, whitespace, exponent notation and exceptional forms.

Mozilla: parseInt. Practical interpretation and numeric-input stringification boundaries.

Return to the Websites subject guide, The Gold Standard of Education, or the How X Works hub.