From e13b9e395a35997cd905ba28860223526971cbb6 Mon Sep 17 00:00:00 2001 From: Frooxius Date: Tue, 9 Apr 2024 19:05:22 +0200 Subject: [PATCH] feat: Add support for providing custom double parser --- Elements.Quantity/Core/QuantityHelper.cs | 11 +++++++++++ Elements.Quantity/Core/Unit.cs | 10 +++++----- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/Elements.Quantity/Core/QuantityHelper.cs b/Elements.Quantity/Core/QuantityHelper.cs index 0360c0a..05bdb1e 100644 --- a/Elements.Quantity/Core/QuantityHelper.cs +++ b/Elements.Quantity/Core/QuantityHelper.cs @@ -6,11 +6,22 @@ namespace Elements.Quantity { + public delegate bool NumberTryParseHandler(string str, NumberStyles numberStyles, IFormatProvider formatProvider, out T value); + public static class QuantityHelper { // CONFIGURATION public static CultureInfo Culture = System.Globalization.CultureInfo.InvariantCulture; + public static NumberTryParseHandler CustomParser; + + public static bool TryParse(string str, NumberStyles numberStyles, IFormatProvider formatProvider, out double value) + { + if (CustomParser != null) + return CustomParser(str, numberStyles, formatProvider, out value); + else + return double.TryParse(str, numberStyles, formatProvider, out value); + } // EXTENSION METHODS diff --git a/Elements.Quantity/Core/Unit.cs b/Elements.Quantity/Core/Unit.cs index 87d5e39..1e4af32 100644 --- a/Elements.Quantity/Core/Unit.cs +++ b/Elements.Quantity/Core/Unit.cs @@ -36,7 +36,7 @@ public ICollection GetUnitNames() var shortBaseNames = t.GetShortBaseNames(); var longBaseNames = t.GetLongBaseNames(); - // cache them - this function will be called by the lirary initializer + // cache them - this function will be called by the library initializer shortBaseName = shortBaseNames[0]; longBaseName = longBaseNames[0]; @@ -46,8 +46,8 @@ public ICollection GetUnitNames() { string unitName = string.Format(name, basename).Trim(); - // need to check - some combinations result in idential names - if (!list.Contains(unitName)) + // need to check - some combinations result in identical names + if (!list.Contains(unitName)) list.Add(unitName); } @@ -121,7 +121,7 @@ static bool ParseIntern(string str, NumberStyles numberStyles, IFormatProvider f bool noUnit = string.IsNullOrWhiteSpace(unitstr); - if(!double.TryParse(valstr, numberStyles, formatProvider, out double val)) + if(!QuantityHelper.TryParse(valstr, numberStyles, formatProvider, out double val)) { if (throwOnFail) throw new FormatException("Number input string was not in a correct format"); @@ -256,5 +256,5 @@ public string FormatAs(T q, string formatNum = null, bool longName = false, } } - + }