Skip to Content
Course content

247: parseInt and parseFloat Edge Cases

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've likely used parseInt and parseFloat a hundred times by now, but in a real production environment, you aren't dealing with clean numbers. You're dealing with user input, which is notoriously messy. I want to show you how these functions behave when things get weird, because if you don't account for the edge cases, you'll end up with NaN poisoning your entire data set.

Parsing "Dirty" Price Strings

Let's say we're building a small checkout utility. Users often type things like "$49.99" or "100 USD" into a field. I want a function that extracts the numeric value regardless of the trailing text. I'll start by writing a quick helper to handle the price.

function parsePrice(input) {
  return parseInt(input);
}

console.log(parsePrice("49.99 USD")); // 49
console.log(parsePrice("100"));       // 100

Wait. I just caught a huge mistake. I used parseInt for a price. If a user enters "49.99", I'm effectively stealing 99 cents from them (or losing it) because parseInt stops the moment it hits a decimal point. It doesn't round; it truncates. For any currency or measurement, parseFloat is the only way to go.

function parsePrice(input) {
  // I'm switching to parseFloat to keep those decimals
  return parseFloat(input);
}

console.log(parsePrice("49.99 USD")); // 49.99
console.log(parsePrice("100"));       // 100

The Trap of Leading Characters and Whitespace

Now, here is where it gets tricky. parseFloat and parseInt are surprisingly forgiving with trailing characters (like "USD" or "px"), but they are absolutely ruthless with leading characters. If the string starts with anything other than a sign (+ or -) or a digit, you get NaN.

If our user types "$49.99" instead of "49.99 USD", our current function fails. Let's look at what happens:

console.log(parsePrice("$49.99")); // NaN

To fix this, I usually strip out common currency symbols or use trim() to handle accidental whitespace. While parseFloat ignores leading whitespace automatically, it's a good habit to be explicit about what you're cleaning. I'll use a simple replace to handle that leading dollar sign.

function parsePrice(input) {
  const cleaned = input.trim().replace('$', '');
  return parseFloat(cleaned);
}

console.log(parsePrice("  $49.99  ")); // 49.99

Handling the "Not a Number" Void

The final edge case that bites engineers is the empty string or a string containing only whitespace. You might expect parseFloat("") to return 0, but it actually returns NaN. In a shopping cart, NaN is a nightmare because any math you do with it (like adding tax) will just result in more NaNs.

I always wrap these calls in a check or provide a fallback value using the logical OR operator or isNaN(). Here is the "production-ready" version of my logic:

function parsePrice(input) {
  if (!input) return 0; // Handle null, undefined, or empty strings immediately
  
  const cleaned = input.trim().replace('$', '');
  const result = parseFloat(cleaned);
  
  // If the result is NaN (e.g., the user typed "abc"), return 0
  return isNaN(result) ? 0 : result;
}

console.log(parsePrice("  $49.99  ")); // 49.99
console.log(parsePrice("Price: 50"));  // NaN (because it starts with 'P')
console.log(parsePrice(""));           // 0

One last tip: if you ever use parseInt for things other than decimals, always provide the second argument—the radix. parseInt("10", 10) tells JS explicitly that you're using base-10. It prevents the engine from guessing if you're using octal or hexadecimal, which can lead to some truly bizarre bugs in older environments.




📋 Practical Task

The Messy Weight Converter

You are building a health app that allows users to enter their weight. However, users are inconsistent; some enter "180lbs", some enter " 75.5 kg ", and some just enter "Unknown".

Create a function called cleanWeight that takes a string input and returns a clean number. Your function must:

  • Remove any leading or trailing whitespace.
  • Correctly parse decimals (e.g., "75.5 kg" should become 75.5).
  • Handle inputs that start with non-numeric characters (like "Weight: 180") by returning 0.
  • Handle completely invalid inputs (like "Unknown" or an empty string) by returning 0 instead of NaN.

Test your function with these cases: " 150lbs ", "82.4 kg", "Unknown", and "".

Rating
0 0

There are no comments for now.

to be the first to leave a comment.