You can use the NumberFormatInfo
class to specify the information that contains the corresponding numeric value. Also, it is important that you test as many inputs as possible to prevent inconsistent values from being stored or generating possible errors or future problems.
I created the StrCurrencyToDecimal()
function to convert the cash value to type decimal
, see:
decimal StrCurrencyToDecimal(string str)
{
NumberFormatInfo infoCurrency = new NumberFormatInfo();
infoCurrency.NegativeSign = "-";
infoCurrency.CurrencyDecimalSeparator = ",";
infoCurrency.CurrencyGroupSeparator = ".";
infoCurrency.CurrencySymbol = "R$";
if (decimal.TryParse(str, NumberStyles.Currency, infoCurrency, out var result))
return result;
return -1;
}
The function returns -1
in case of invalid values, it's just for illustration, however, there are more appropriate ways for this, you can even use error codes. Read this answer that addresses this issue.
See the complete code:
using System.Globalization;
using static System.Console;
public class Program
{
public static void Main()
{
WriteLine("Valor: {0}", StrCurrencyToDecimal("R$3.852,00"));
WriteLine("Valor: {0}", StrCurrencyToDecimal("R$0,00"));
WriteLine("Valor: {0}", StrCurrencyToDecimal("R$-3.852,00"));
WriteLine("Valor: {0}", StrCurrencyToDecimal(""));
WriteLine("Valor: {0}", StrCurrencyToDecimal("R3.852,00"));
WriteLine("Valor: {0}", StrCurrencyToDecimal("$3.852,00"));
WriteLine("Valor: {0}", StrCurrencyToDecimal("3.852,00"));
WriteLine("Valor: {0}", StrCurrencyToDecimal("R$3ad.852,00"));
WriteLine("Valor: {0}", StrCurrencyToDecimal("R$3,852.00"));
WriteLine("Valor: {0}", StrCurrencyToDecimal("assR$3,852.00"));
}
static decimal StrCurrencyToDecimal(string str)
{
NumberFormatInfo infoCurrency = new NumberFormatInfo();
infoCurrency.NegativeSign = "-";
infoCurrency.CurrencyDecimalSeparator = ",";
infoCurrency.CurrencyGroupSeparator = ".";
infoCurrency.CurrencySymbol = "R$";
if (decimal.TryParse(str, NumberStyles.Currency, infoCurrency, out var result))
return result;
return -1;
}
}
Output:
Value: 3852.00
Value: 0.00
Value: -3852.00
Value: -1
Value: -1
Value: -1
Value: -1
Value: -1
Value: -1
Value: -1
See working at .NET Fiddle .
Learn more about NumberFormatInfo class .