Skip to content

Commit

Permalink
feat: Add support for providing custom double parser
Browse files Browse the repository at this point in the history
  • Loading branch information
Frooxius committed Apr 9, 2024
1 parent 6320490 commit e13b9e3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
11 changes: 11 additions & 0 deletions Elements.Quantity/Core/QuantityHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,22 @@

namespace Elements.Quantity
{
public delegate bool NumberTryParseHandler<T>(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<double> 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

Expand Down
10 changes: 5 additions & 5 deletions Elements.Quantity/Core/Unit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public ICollection<string> 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];

Expand All @@ -46,8 +46,8 @@ public ICollection<string> 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);
}

Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -256,5 +256,5 @@ public string FormatAs(T q, string formatNum = null, bool longName = false,
}
}


}

0 comments on commit e13b9e3

Please sign in to comment.