Recent chats
ASKGEEZ Q&A GUIDETechnology & devices

How can I convert a string to a number without confusing zero and invalid input?

Quick answer

Use Number(text) to convert the string, then test the result with Number.isNaN(value). Don’t use if (!value) to detect failure: both zero and NaN are falsy. Also choose an explicit rule for empty or whitespace-only input, because Number() converts those strings to zero. If your application treats empty input as missing, check for it before converting.

LET’S WORK THROUGH IT

The question, the details, the next step.

Question

I need to turn a text field into a number. What’s the basic pattern, and how do I tell a real zero from a failed conversion?

Geez

Convert first, then check specifically for NaN:

function convertText(text) {
  const value = Number(text);
  return Number.isNaN(value)
    ? { ok: false, reason: "invalid number" }
    : { ok: true, value };
}

For example, convertText("0") returns { ok: true, value: 0 }, while convertText("hello") returns { ok: false, reason: "invalid number" }. Number() converts strings to numbers and produces NaN when conversion fails; Number.isNaN() checks whether the result is that numeric NaN value.[S1][S2] The ok field keeps success separate from the converted value, so zero remains an ordinary successful result.

Follow-up question

Why not just write if (!value) to catch the bad conversion?

Geez

Because that condition doesn’t mean “conversion failed.” It treats zero as falsy, and NaN is falsy too, so a valid converted zero gets lumped together with invalid text.[S2]

For instance:

const zero = Number("0");
const bad = Number("hello");

console.log(!zero); // true
console.log(!bad);  // true
console.log(Number.isNaN(zero)); // false
console.log(Number.isNaN(bad));  // true

Use Number.isNaN(value) for the conversion-failure check. It checks for the NaN value without first coercing its argument.[S2] The important order is to convert the input, then inspect that converted result. Don’t use a truthiness check as a substitute.

Follow-up question

What happens with an empty field? I don’t want a blank answer to quietly become zero.

Geez

That needs a separate input rule: Number("") produces zero, and whitespace-only text also converts to zero. Leading and trailing whitespace around other text is ignored during conversion.[S1] So Number.isNaN(Number("")) is false; the conversion succeeded as far as Number() is concerned, even if your form should treat a blank as missing.

If blank or whitespace-only input should be rejected, check it before conversion:

function convertNonBlankText(text) {
  if (text.trim() === "") {
    return { ok: false, reason: "empty input" };
  }

  const value = Number(text);
  if (Number.isNaN(value)) {
    return { ok: false, reason: "invalid number" };
  }
  return { ok: true, value };
}

Here, " " is rejected as empty, "0" is accepted as zero, and "hello" is rejected as invalid. This example assumes the input is a string and that blank text is not allowed; choose a different empty-input rule if your application needs one.

Follow-up question

Can you show the outputs together so I can check my implementation?

Geez

With convertNonBlankText above, the expected results are:

  1. convertNonBlankText("23") → { ok: true, value: 23 }
  2. convertNonBlankText("0") → { ok: true, value: 0 }
  3. convertNonBlankText("") → { ok: false, reason: "empty input" }
  4. convertNonBlankText(" ") → { ok: false, reason: "empty input" }
  5. convertNonBlankText("hello") → { ok: false, reason: "invalid number" }

These illustrate the conversion and checks described here; they aren’t a substitute for testing your full application. The source material establishes the behavior of Number() and Number.isNaN() for these cases, but it doesn’t define what your particular form should accept. Decide whether blanks are allowed, then make that rule explicit in the function and its output.

A practical checklist

  • Decide whether empty and whitespace-only strings count as missing or should convert to zero.

  • Convert the input with Number(text).

  • Use Number.isNaN(value) to identify a failed conversion.

  • Keep success status separate from the numeric value so zero remains valid.

  • Check representative numeric, zero, blank, whitespace, and invalid inputs.

A few more useful answers

Does `Number.isNaN(Number(""))` detect an empty string?

No. Number("") produces zero, so Number.isNaN() returns false. Check for empty input separately if your application should reject it.[S1]

Why use `Number.isNaN()` instead of checking whether the value is falsy?

A falsy check treats valid zero and NaN alike. After conversion, Number.isNaN(value) specifically detects the NaN result.[S2]

Sources

References used for this guide.

  1. [S1] Number — JavaScript | MDN
    developer.mozilla.org · Checked
  2. [S2] NaN — JavaScript | MDN
    developer.mozilla.org · Checked

YOUR QUESTION. YOUR DETAILS.

Let’s work through your situation.

Get a tailored answer or help with your next task. Starts at $1, with a quote before you pay.

Ask your own question
← Back to Geez at Work