Snippet
Parse a typed USD amount on the host, not in the model
A complete C# parser that turns amounts like 5,000.35 into cents with integer math and rejects anything ambiguous.
AI-generated, human-reviewed: the first draft was generated by an AI agent; I fact-checked, tested, and edited it. AI use policy
What it does#
Turns a USD amount the way a person types it, such as 5000, 5,000.35, or $5000.3, into
cents. It uses integer math, accepts commas only in correct thousands groups, allows at most two
decimal places, and rejects anything else: signs, exponents, spaces inside the number, the
other decimal convention, words, zero, overflow, and non-ASCII digits. Format turns cents
back into an invariant display string such as 5,000.00.
The model passes the amount as a string, exactly as the user said it. The host decides what it means.
You need#
- .NET 10 (the regex uses the
GeneratedRegexsource generator) - A tool or endpoint that receives an amount as text, for example a
prepare_transfertool
Where it goes#
Add the file to the project that hosts your agent tools and call UsdAmount.TryParseMinor
before you build any proposal. Keep your cap and currency checks where they are; this class
only parses.
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Sarang Datye
using System.Globalization;
using System.Text.RegularExpressions;
/// <summary>
/// Parses a USD amount the way a person types it ("5000", "5,000.35", "$5000.3") into cents.
/// Integer math only. The caller still enforces the cap and the currency.
/// </summary>
public static partial class UsdAmount
{
[GeneratedRegex(@"\A\$?(?<whole>[0-9]+|[0-9]{1,3}(?:,[0-9]{3})+)(?:\.(?<fraction>[0-9]{1,2}))?\z", RegexOptions.CultureInvariant)]
private static partial Regex Pattern();
public static bool TryParseMinor(string? text, out long minor)
{
minor = 0;
if (text is null || text.Length > 32) return false;
var match = Pattern().Match(text.Trim());
if (!match.Success) return false;
var whole = match.Groups["whole"].Value.Replace(",", "", StringComparison.Ordinal);
var fraction = match.Groups["fraction"].Value.PadRight(2, '0');
if (!long.TryParse(whole, NumberStyles.None, CultureInfo.InvariantCulture, out var units) ||
!long.TryParse(fraction, NumberStyles.None, CultureInfo.InvariantCulture, out var cents))
return false;
try { minor = checked(units * 100 + cents); }
catch (OverflowException) { minor = 0; return false; }
if (minor > 0) return true;
minor = 0;
return false;
}
/// <summary>Invariant display with thousands separators, for example 500035 becomes "5,000.35".</summary>
public static string Format(long minor) => (minor / 100m).ToString("#,0.00", CultureInfo.InvariantCulture);
}
Check that it works#
UsdAmount.TryParseMinor("5,000.35", out var cents); // true, cents == 500035
UsdAmount.TryParseMinor("5.000,35", out _); // false
UsdAmount.TryParseMinor("5000 USD", out _); // false
UsdAmount.Format(500000); // "5,000.00"