105 lines
3.7 KiB
C#
105 lines
3.7 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
|
|
namespace DeukBot4.Utilities
|
|
{
|
|
public class EnglishNumberParser
|
|
{
|
|
private static readonly Dictionary<string, int> OneValues = new Dictionary<string, int>()
|
|
{
|
|
{"zero", 0}, {"a", 1}, {"an", 1}, {"one", 1}, {"two", 2}, {"three", 3}, {"four",4}, {"five", 5}, {"six", 6}, {"seven", 7},
|
|
{"eight", 8}, {"nine", 9}
|
|
};
|
|
private static readonly Dictionary<string, int> TenValues = new Dictionary<string, int>()
|
|
{
|
|
{"ten", 10}, {"eleven", 11}, {"twelve", 12}, {"thirteen", 13}, {"fourteen", 14}, {"fifteen", 15},
|
|
{"sixteen", 16}, {"seventeen", 17}, {"eighteen", 18}, {"nineteen", 19},
|
|
|
|
{"twenty", 20}, {"thirty", 30}, {"forty",40}, {"fifty", 50}, {"sixty", 60}, {"seventy", 70},
|
|
{"eighty", 80}, {"ninety", 90}
|
|
};
|
|
private static readonly Dictionary<string, int> HundredsValues = new Dictionary<string, int>()
|
|
{
|
|
{"hundred", 100}, {"thousand",1000}, {"million", 1_000_000}
|
|
};
|
|
|
|
|
|
public static bool ConvertNumberString(string numberString, out double number)
|
|
{
|
|
numberString = numberString.Replace("-", "").Replace(" ", "");
|
|
var i = 0;
|
|
while (numberString.Length > 0)
|
|
{
|
|
var next = ConvertNextNumber(ref numberString);
|
|
if (!next.HasValue)
|
|
{
|
|
number = 0;
|
|
return false;
|
|
}
|
|
i += next.Value;
|
|
}
|
|
number = i;
|
|
return true;
|
|
}
|
|
|
|
private static int? ConvertNextNumber(ref string numberString)
|
|
{
|
|
foreach (var oneValue in OneValues)
|
|
{
|
|
if (numberString.EndsWith(oneValue.Key, StringComparison.InvariantCultureIgnoreCase))
|
|
{
|
|
numberString = numberString.Substring(0, numberString.Length - oneValue.Key.Length);
|
|
return oneValue.Value;
|
|
}
|
|
}
|
|
foreach (var oneValue in TenValues)
|
|
{
|
|
if (numberString.EndsWith(oneValue.Key, StringComparison.InvariantCultureIgnoreCase))
|
|
{
|
|
numberString = numberString.Substring(0, numberString.Length - oneValue.Key.Length);
|
|
return oneValue.Value;
|
|
}
|
|
}
|
|
foreach (var oneValue in HundredsValues)
|
|
{
|
|
if (numberString.EndsWith(oneValue.Key, StringComparison.InvariantCultureIgnoreCase))
|
|
{
|
|
numberString = numberString.Substring(0, numberString.Length - oneValue.Key.Length);
|
|
var value = oneValue.Value;
|
|
var next = ConvertNextNumber(ref numberString);
|
|
if (next.HasValue)
|
|
{
|
|
if ((int)Math.Log10(next.Value) <= (int)Math.Log10(value))
|
|
value *= next.Value;
|
|
else
|
|
{
|
|
value += next.Value;
|
|
}
|
|
}
|
|
return value;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
|
|
public static string GetShortOrdinalNumber(int number)
|
|
{
|
|
var tensDigit = number % 100 / 10;
|
|
if (tensDigit == 1) return $"{number}th";
|
|
switch (number % 10)
|
|
{
|
|
case 1:
|
|
return $"{number}st";
|
|
case 2:
|
|
return $"{number}nd";
|
|
case 3:
|
|
return $"{number}rd";
|
|
default:
|
|
return $"{number}th";
|
|
}
|
|
|
|
}
|
|
}
|
|
} |