Path: redb/redb.Core/Utils/RedbDecimal.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Utils/RedbDecimal.cs ---- using System.Globalization; namespace redb.Core.Utils; /// /// A decimal from a binary floating-point value, the way a reader of a REAL or FLOAT column, an aggregate over one or a /// computed result needs it: the decimal of the shortest text that reads back as the same double ("R"). So 123.45 /// stored as REAL comes back as 123.45 on every runtime. /// /// /// The explicit conversion (decimal)double, which and /// use, rounds to 15 significant digits up to .NET 10 (12345678901234.56 /// became 12345678901234.6) and gives the exact binary value from .NET 11 on (123.45 became /// 123.45000000000000284217094304). Neither is the number that was stored. /// public static class RedbDecimal { /// The decimal the double stands for. A value outside the decimal range, NaN or an infinity throws /// , as the explicit conversion does. public static decimal FromDouble(double value) { if (double.IsNaN(value) || double.IsInfinity(value)) throw new OverflowException($"{value.ToString(CultureInfo.InvariantCulture)} has no decimal value."); // The shortest text of a double is at most 24 characters ("-1.7976931348623157E+308"): formatted on the stack, // parsed from the span, no string per value on the read path. Span text = stackalloc char[32]; value.TryFormat(text, out var written, "R", CultureInfo.InvariantCulture); return decimal.Parse(text[..written], NumberStyles.Float, CultureInfo.InvariantCulture); } /// The decimal the float stands for (the shortest text of the float itself, not of its widening to double). public static decimal FromSingle(float value) { if (float.IsNaN(value) || float.IsInfinity(value)) throw new OverflowException($"{value.ToString(CultureInfo.InvariantCulture)} has no decimal value."); Span text = stackalloc char[32]; value.TryFormat(text, out var written, "R", CultureInfo.InvariantCulture); return decimal.Parse(text[..written], NumberStyles.Float, CultureInfo.InvariantCulture); } /// /// with a double or a float read through /// / . Anything else converts as before. /// public static decimal From(object value) => value switch { decimal d => d, double dbl => FromDouble(dbl), float f => FromSingle(f), _ => Convert.ToDecimal(value, CultureInfo.InvariantCulture) }; /// /// , except that a double or a float asked for as a /// decimal goes through / . Every other pair converts exactly as /// does with the same provider (null: the current /// culture, as ). /// public static object ChangeType(object value, Type targetType, IFormatProvider? provider = null) => targetType == typeof(decimal) && value is double or float ? From(value) : Convert.ChangeType(value, targetType, provider); }