1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
public static class NumberNormalizer2 { private static readonly Regex StrictThousandsGroups = new Regex(@"\A[+-]?\d{1,3}(,\d{3})+\z", RegexOptions.Compiled);
public static bool TryNormalizeToDot(string value, out string normalized) { normalized = null; if (string.IsNullOrWhiteSpace(value)) return false;
string s = value.Trim(); int lastDot = s.LastIndexOf('.'); int lastComma = s.LastIndexOf(',');
if (lastDot >= 0 && lastComma >= 0) { string candidate = lastDot > lastComma ? s.Replace(",", "") : s.Replace(".", "").Replace(',', '.'); return TryFinalize(candidate, out normalized); }
if (lastComma >= 0) { string candidate = StrictThousandsGroups.IsMatch(s) ? s.Replace(",", "") : s.Replace(',', '.'); return TryFinalize(candidate, out normalized); }
return TryFinalize(s, out normalized); }
private static bool TryFinalize(string candidate, out string normalized) { normalized = null; if (decimal.TryParse(candidate, NumberStyles.Float, CultureInfo.InvariantCulture, out _)) { normalized = candidate; return true; } return false; }
public static bool TryGetValFromModel<T>(string numStr, out T val) where T : struct, IParsable<T> { val = default(T); if (!TryNormalizeToDot(numStr, out string formateStr)) return false; if (T.TryParse(formateStr, CultureInfo.InvariantCulture, out T _tmpLimit)) { val = _tmpLimit; return true; } return false; } }
|