Skip to content

Numeric and String Extensions

Ilia Petrov-Komotskii edited this page Oct 16, 2026 · 5 revisions

Clamp, remap, saturating int math, clock strings, and culture-invariant parsing.

Numeric

using Mane.DotNet;

int hp = damage.Clamp(0, 100);
float t = x.Clamp01();
float ui = health.Remap(0f, maxHp, 0f, 1f); // does not clamp the result
int sum = a.SafePlus(b);                    // saturates on overflow
bool even = n.IsEven();
  • Clamp(min, max) — generic IComparable<T>; min > max throws.
  • ClampMin / ClampMax — one-sided.
  • Clamp01 — float, double, decimal.
  • Remap — linear map. Zero-width source range returns destFrom. Result is not clamped to the destination.
  • SafePlus / SafeMinus / SafeMultiply — saturating int arithmetic.

TimeSpan

Hours/minutes are total duration, not wrapped mod 24/60. Negative and zero format as zeros.

TimeSpan.FromHours(26).ToHHMMSS(); // 26:00:00
TimeSpan.FromMinutes(90).ToMMSS(); // 90:00
TimeSpan.Zero.ToHHMM();            // 00:00

Strings

Invariant number parsers trim whitespace and apostrophes. The last . or , is the decimal separator; extra marks of the same kind are thousands separators. Null/empty/invalid → defaultValue (no throw). Integers also accept a whole number with a zero fractional part (1.000).

int n = "1.000".ParseIntInvariant();       // 1 — zero fractional part is allowed
float f = "1.234,5".ParseFloatInvariant(); // last comma is decimal → 1234.5
"hello".ToFirstUpperInvariant();           // Hello, on every machine
"istanbul".ToFirstUpper(new CultureInfo("tr-TR")); // İstanbul

int apples = 21;
string label = apples.GetCountedString("яблоко", "яблока", "яблок");
string english = 2.GetCountedString("apple", "apples");

ToFirstUpper and ToFirstUpperInvariant uppercase the first character, like ToUpper and ToUpperInvariant for the whole string. ToFirstUpper uses the culture you pass, or the current culture. In a Unity player that is the player's OS locale, not your game's language, so on a Turkish system "item".ToFirstUpper() gives "İtem" even in an English UI. Use ToFirstUpperInvariant for keys, generated names, and any text that must come out the same on every machine. Null and whitespace-only strings are returned unchanged.

GetCountedString(one, many, more) is Slavic-style (count % 100 / % 10): 1, 21 → one; 2–4, 22–24 → many; everything else (0, 5–20, 25, 11–19, …) → more. The sign is ignored, so -21 → one.

GetCountedString(one, many) is English-style: counts greater than 1 use many (2 → apples). 1, 0, and negative counts use one. Null templates throw.

Clone this wiki locally