Skip to main content
Version: 3.0.8

Parse localized number words

Orientation

Use TryToNumber at an input boundary where invalid words are expected. Use ToNumber when invalid text is exceptional and should throw. Both require an explicit CultureInfo, because the same words and token rules do not mean the same thing in every language.

Example

This executable parses a positive phrase, a negative phrase, and an invalid token using the stable int result:

Program.cs
using System.Globalization;
using Humanizer;

var culture = CultureInfo.GetCultureInfo("en-US");

var parsed = "two hundred five".ToNumber(culture);
var succeeded = "negative forty-two".TryToNumber(
out var negative,
culture,
out var unrecognized);
var rejected = "two otters".TryToNumber(
out var invalid,
culture,
out var invalidWord);

AssertEqual(205, parsed);
AssertEqual(true, succeeded);
AssertEqual(-42, negative);
AssertEqual(null, unrecognized);
AssertEqual(false, rejected);
AssertEqual(0, invalid);
AssertEqual("otters", invalidWord);

Console.WriteLine("205; -42; rejected at otters");

static void AssertEqual<T>(T expected, T actual)
{
if (!EqualityComparer<T>.Default.Equals(expected, actual))
throw new InvalidOperationException($"Expected '{expected}', got '{actual}'.");
}

Handle expected failure

The longest TryToNumber overload returns:

  • false when a token cannot be recognized.
  • 0 in the numeric result.
  • The first unrecognized word in the final out parameter.

That token is useful for field validation messages. Do not catch FormatException for routine input when TryToNumber expresses the branch directly.

Pitfall

The parser supports only the locales and word forms represented by its selected-version converter. It is not a general natural-language parser. Preserve the explicit culture from the user-input boundary and do not silently fall back to English for an unsupported locale.

Version notes

Words-to-number begins in Humanizer 3.0.1 and returns int through 3.0.10.