Reputation: 1842
I'm wondering if there's simple way to check if a string is in a value format of any kind. Meaning the number one-thousand could be represented in any of the following ways:
I've tried double.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out n)
but that isn't working for items with the currency symbol out in front. So I tried double.TryParse(value NumberStyles.Any | NumberStyles.AllowCurrencySymbol, CultureInfo.InvariantCulture, out n)
but that is also not working.
Basically I'd like to check if a value can be considered a number value at all.
Upvotes: 0
Views: 764
Reputation: 706
You can use regular expressions
https://regexone.com/references/csharp
you can use below code to accept your cases
$1,000.00
string pattern = @"^\$?(\d{1,3}(\,\d{3})*(\.0{2})?)|(\d+(\.0{2})?)$";
Match result = Regex.Match("$100,000.00", pattern);
if (result.Success)
// your input is in format
Upvotes: 0
Reputation: 25623
The invariant culture does not use $
as its currency symbol; it uses ¤
.
Picking the correct culture for parsing is tricky. Obviously, it is best to use the same culture that was used to format the value to begin with. If you know which culture was used, you’re lucky :).
By default, unless a specific culture is specified, CurrentCulture
will be used. The current culture can be overridden and set on a per-thread basis, but it defaults to the locale settings of the host operating system. In the absence of other information, CurrentCulture
is a reasonable first guess.
I would suggest you ||
together at least two TryParse
calls: one for CurrentCulture
(or your best guess as to the culture of origin), and a fallback using InvariantCulture
. Include AllowCurrencySymbol
on both.
Upvotes: 1