1
0

UserInputParser.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System.Globalization;
  2. namespace Content.Shared.Localizations;
  3. /// <summary>
  4. /// Helpers for user input parsing.
  5. /// </summary>
  6. /// <remarks>
  7. /// A wrapper around the <see cref="System.Single.TryParse(string, out float)"/> API,
  8. /// with the goal of trying more options to make the user input parsing less restrictive.
  9. /// For culture-invariant parsing use <see cref="Robust.Shared.Utility.Parse"/>.
  10. /// </remarks>
  11. public static class UserInputParser
  12. {
  13. private static readonly NumberFormatInfo[] StandardDecimalNumberFormats = new[]
  14. {
  15. new NumberFormatInfo()
  16. {
  17. NumberDecimalSeparator = "."
  18. },
  19. new NumberFormatInfo()
  20. {
  21. NumberDecimalSeparator = ","
  22. }
  23. };
  24. public static bool TryFloat(ReadOnlySpan<char> text, out float result)
  25. {
  26. foreach (var format in StandardDecimalNumberFormats)
  27. {
  28. if (float.TryParse(text, NumberStyles.Integer | NumberStyles.AllowDecimalPoint, format, out result))
  29. {
  30. return true;
  31. }
  32. }
  33. result = 0f;
  34. return false;
  35. }
  36. public static bool TryDouble(ReadOnlySpan<char> text, out double result)
  37. {
  38. foreach (var format in StandardDecimalNumberFormats)
  39. {
  40. if (double.TryParse(text, NumberStyles.Integer | NumberStyles.AllowDecimalPoint, format, out result))
  41. {
  42. return true;
  43. }
  44. }
  45. result = 0d;
  46. return false;
  47. }
  48. }