In C#, I'm trying to convert a string to decimal.
For example, the string is "(USD 92.90)"
How would you parse this out as a decimal with Decimal.Parse fcn.
I'm going on the assumption here that the string you're trying to parse is an actual currency value.
CultureInfo c = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
c.NumberFormat.CurrencyNegativePattern = 14; // From MSDN -- no enum values for this
c.NumberFormat.CurrencySymbol = "USD";
decimal d = Decimal.Parse("(USD 92.90)", NumberStyles.Currency, c);
您可以从reg-exp开始提取数字部分,然后使用Decimal.TryParse来解析子字符串。
First, get the number out of the string. A Regex \\d+(.\\d+)?
might help there. Although you could use substring, if the characters around that number are always the same.
Then use Decimal.Parse (or Double.Parse) on that string.
When parsing strings, I always prefer to use TryParse to avoid exceptions being thrown for invalid strings:
string str = "(USD 92.90)";
decimal result;
if (Decimal.TryParse(str, out result))
{
// the parse worked
}
else
{
// Invalid string
}
And as others have said, first use a regular expression to extract just the numerical part.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.