converting string to decimal in c# - c#

I am having some problems converting string to decimal values with decimal.parse.
This is the line of code I have:
fixPrice = decimal.Parse(mItemParts.Groups["price"].Value.Replace("$", "").Replace(" ", "").Replace("usd", ""));
The value from which I am trying to convert is: '$779.99'
Then once the parsing to decimal happens, I am getting this value: 77999.
I would like to get 779.99 instead of 77999.
Thanks in advance, Laziale
Regex included: "#"\[^\""]+?)\""[^~]+?\]+?src=\""(?[^\""]+?)\""[^>]+?title=\""(?[^\""]+?)\""[^~]+?price\"">(?[^\<]+?)\<[^~]+?\(?[^\<]+?)\

I would use Decimal.TryParse():
decimal parsedDecimal = 0;
string yourCurrency = "$779.99";
bool didParse = Decimal.TryParse(yourCurrency,
NumberStyles.Currency,
new CultureInfo("en-US"), out parsedDecimal);
if(didParse) {
// Parse succeeded
}
else {
// Parse failed
}

It appears that you are running this in a culture where '.' is the group separator, and ',' is the decimal separator. To get around that, use the Parse overload that takes a CultureInfo:
fixPrice = decimal.Parse(stringExpression, CultureInfo.InvariantCulture);
Also look into the NumberStyles enum so you don't have to worry about currency signs yourself:
fixPrice = decimal.Parse(stringExpression, NumberStyles.Currency, new CultureInfo("en-US"));

Pass a CultureInfo instance of the culture you are parsing from.
CultureInfo inherits from IFormatProvider
edit:
Here is a sample for the conversion
Decimal.Parse(yourValue, NumberStyles.AllowCurrencySymbol |
NumberStyles.AllowDecimalPoint |
NumberStyles.AllowThousands,
CultureInfo.InvariantCulture);

This works for me:
string decStr = "$779.99";
CultureInfo ci = new CultureInfo("en-US");
decimal fixPrice = decimal.Parse(decStr, NumberStyles.Currency, ci);

Related

Globalization .net convert string to double

İ have string like this and i want to convert it to double.
string x = "65.50";
double y = Convert.ToDouble(x);
But the result is 6550.0
i want it to be 65.50.
I am using ASP.NET and C#. I think it is a problem about globalization.
This is my for question sorry about that (:
Yes, it's your current culture that converts it this way. You can use CultureInfo.InvariantCulture to skip using your culture.
double d = double.Parse("65.50", CultureInfo.InvariantCulture);
i want it to be 65.50.
If you want to convert it back to string:
string str = d.ToString("N2", CultureInfo.InvariantCulture);
I assume this is a currency since you keep the decimal places. Then you should use decimal instead:
decimal dec = decimal.Parse("65.50", CultureInfo.InvariantCulture); // 65.5
Now you can use decimal.ToString and it automagically restores the decimal places:
string str = dec.ToString(CultureInfo.InvariantCulture); // "65.50"
Recently i had a similar problem. The solution :
var result = Double.TryParse(x, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out y);
if you get true, that's x is converted to double
Try this:
var res = Double.Parse("65.50", NumberStyles.Float, CultureInfo.InvariantCulture);
It will parse it with culture where . is floating separator
Here you can try it: http://ideone.com/3LMVqa

decimal.TryParse returns false

The input string in textbox is, say, $10.00 . I call
decimal result;
var a = decimal.TryParse(text, NumberStyles.AllowCurrencySymbol, cultureInfo, out result);
cultureInfo is known (en-US). Why does decimal.tryParse returns false?
Thank you.
The problem is you've allowed the currency symbol itself, but you've omitted other properties that are required to parse it correctly (decimal point, for example.) What you really want is NumberStyles.Currency:
decimal.TryParse("$10.00", NumberStyles.Currency, cultureInfo, out result);
Try this, you need to include NumberStyles.Number in the bitwise combination of values for the style argument:
decimal result;
var a = decimal.TryParse(text, NumberStyles.Number | NumberStyles.AllowCurrencySymbol, cultureInfo, out result);
You forgot to allow the decimal point, too:
decimal result;
var enUS = new System.Globalization.CultureInfo("en-US");
var a = decimal.TryParse("$10.00", System.Globalization.NumberStyles.AllowCurrencySymbol | System.Globalization.NumberStyles.AllowDecimalPoint , enUS, out result);
Console.WriteLine(enUS);
Console.WriteLine(a);
Console.WriteLine(result);

Parsing floats with Single.TryParse fails

There is an article on Single.TryParse over at MSDN with this example code:
http://msdn.microsoft.com/en-us/library/26sxas5t%28v=vs.100%29.aspx
// Parse a floating-point value with a thousands separator.
value = "1,643.57";
if (Single.TryParse(value, out number))
Console.WriteLine(number);
else
Console.WriteLine("Unable to parse '{0}'.", value);
Problem is in the article the TryParse returns true and the string is converted, but when I try it, it's false. How do I fix this?
UPD: To simplify parsing, these two lines can be used:
NumberStyles style = System.Globalization.NumberStyles.Any;
CultureInfo culture = CultureInfo.InvariantCulture;
This setting allows for negative floats and strings with leading and trailing space characters to be parsed.
you need to set culture like this
using System.Globalization;
string value = "1345,978";
NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint;
CultureInfo culture = System.Globalization.CultureInfo.CreateSpecificCulture("fr-FR");
if (Single.TryParse(value, style, culture, out number))
Console.WriteLine("Converted '{0}' to {1}.", value, number);
else
Console.WriteLine("Unable to convert '{0}'.", value);
from msdn : Single.TryParse Method (String, NumberStyles, IFormatProvider, Single%)
or
float usedAmount;
// try parsing with "fr-FR" first
bool success = float.TryParse(inputUsedAmount.Value,
NumberStyles.Float | NumberStyles.AllowThousands,
CultureInfo.GetCultureInfo("fr-FR"),
out usedAmount);
if (!success)
{
// parsing with "fr-FR" failed so try parsing with InvariantCulture
success = float.TryParse(inputUsedAmount.Value,
NumberStyles.Float | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture,
out usedAmount);
}
if (!success)
{
// parsing failed with both "fr-FR" and InvariantCulture
}
Answered over here : C# float.tryparse for French Culture
You have problem with your culture about : , character
You can use CultureInvariant in your string

How do I convert a string to a decimal, and format it for pretty output?

I want to convert "372551.40" to decimal. But I need to see it after converting this format 372.551,40.
To convert it to decimal, you can use:
decimal decimalValue = 0.0;
decimalValue = decimal.Parse("372551.40");
or
decimal.TryParse("372551.40", out decimalValue);
To display it in a specific format you can do:
CultureInfo tr = new CultureInfo("tr-TR");
string formattedValue = decimalValue.ToString("c", tr);
//result will be 372.551,40 YTL
formattedValue = decimalValue.ToString("0,0.00", tr);
//result will be 372.551,40
string value;
Decimal number;
value = "16,523,421";
if (!Decimal.TryParse(value,out number))
{
// set it to something if the "Value" is not a number
number = -1;
}
Do the following:
string s = "372551.40";
CultureInfo cultureInfo = CultureInfo.InvariantCulure; //Use relevant culture in which your number is formatted. In this case InvariantCulture would do.
decimal d;
bool succesful = Decimal.TryParse(s, NumberStyles.Number, cultureInfo, out d); //it will try to parse the string according to the specified culture.;
If you have a succesful parse, then d will store the numeric value represented by s as a decimal value which you can output into any formatted string and culture the ToString() or Format.String().
Note that if the culture in which the number represented by s is the current system culture, then you can use the TryParse(string s, out decimal d) overload where it is not necessary to specify NumberStyles and IFormatProvider.
Something like this?
string s = "372551.40";
decimal d;
if (decimal.TryParse(s, out d))
{
var culture = new CultureInfo("de-DE");
var result = d.ToString("0,0.00", culture);
// result is "372.551,40"
}
You can also use the current culture instead of hard-coding one like I did.
Hope this helps,
John
Use decimal.Parse() to make it a decimal. Then you have many formatting options.
The display as you mentioned is dependent on the culture setting.
Make your new CultureInfo and in the NumberFormat, you will have to modify some settings like Decimal Separator as , and Thousands Separator as . and provide this to the ToString method of the variable holding the decimal value.
This should display the value as 372.551,40
You can use .Replace
string string 1 = "372,551.40";
string1.Replace(",","");
decimalVal = System.Convert.ToDecimal(StringVal);
//shows 372551.40
You can always throw that into a for loop if you are playign with a ton of numbers.
You can find more in depth info and some examples on MSDN
The overload of decimal.Parse that takes an IFormatProvider will allow you to parse strings containing numbers with periods as decimal point symbols (in case the standard is a comma in your culture).
You can use ToString on the resulting decimal to format it with a comma by passing in an appropriate IFormatProvider. Both CulturInfo and NumberFormatInfo implement IFormatProvider.
You can get an instance of CultureInfo with the following code (this one is for English in Australia).
new CultureInfo("en-AU")
Also note that decimal.TryParse is a good alternative to the decimal.Parse method if you expect incorrectly formatted strings as it will allow you to handle them without an exception being raised.
The following code should give you the desired result (you wrote in one of the comments that the target system is SAP and that the culture is probably German (de-DE)).
var yourString = "372551.40";
var yourDecimal = decimal.Parse(yourString, CultureInfo.InvariantCulture);
var yourFormattedDecimal = yourDecimal.ToString(new CultureInfo("de-DE"));
From MSDN:
string value;
decimal number;
// Parse an integer with thousands separators.
value = "16,523,421";
number = Decimal.Parse(value);
Console.WriteLine("'{0}' converted to {1}.", value, number);
// Displays:
// 16,523,421' converted to 16523421.
Cheers
You can create custom NumberFormatInfo:
string s = "372551.40";
var dec = decimal.Parse(s, CultureInfo.InvariantCulture);
var nfi = new CultureInfo("en-US", false).NumberFormat;
nfi.NumberGroupSeparator = ".";
nfi.NumberDecimalSeparator = ",";
var res = dec.ToString("n", nfi);
var resDecimal = decimal.Parse(res, nfi);
Output is exactly what you need: 372.551,40

Having difficulties converting a string into decimal

Thanks for taking the time to assist me with my problem.
In the code I'm writing, I'm iterating through a table, I get the appropriate values (confirmed it using the debugger) and I'm parsing them to the appropriate types before and finally I add them to an Object to be serialized into XML.
However, I bumped into a problem and that is I can't seem to find a way to parse the string into a decimal value. Take a look:
if (DateTime.TryParse(dateString, culture, styles, out date))
{
decimal LastValue;
string vrednost = String.Format("{0:0,0.0}",
row.SelectSingleNode("td[2]").InnerText);
if (Decimal.TryParse(vrednost, out LastValue))
list.Add(new StockEntry
{
Date = date,
PoslednaCena = LastValue
...
}
Note that the value of vrednost is 4.451,00 and I suspect that if I convert it to 4,451.00 it will get parsed.
I've succeeded in parsing date into the appropriate datetime value. However, the value of LastValue is always 0. I've exhausted all the resources that I know of. Do you have any idea how to solve my problem?
Thank you in advance!
This formatting will do nothing because you can't format strings like this. You have to use parse method with additional parameters and specify your own format
string s2 = "4.451,00";
NumberFormatInfo numberFormatInfo = new NumberFormatInfo();
numberFormatInfo.NumberDecimalSeparator = ",";
numberFormatInfo.NumberGroupSeparator = ".";
var d = decimal.Parse(s2, numberFormatInfo);
I think that your problem might be due to the culture used for the parsing. Try using CultureInfo.InvariantCulture for your parsing. It should work with "," as thousands separator and "." as decimal separator.
Decimal.TryParse(vrednost, NumberStyles.Number, CultureInfo.InvariantCulture, out LastValue);
If you want to swap them you could use another culture. Italian, for instance, works with your format (not sure about the others), so your code for "4.451,00" would look like:
Decimal.TryParse(vrednost, NumberStyles.Number, CultureInfo.GetCultureInfo("it"), out LastValue);
If you want to use a custom culture instead of forcing some culture which does what you want you can simply create your NumberFormatInfo class and pass it to the parse method.
NumberFormatInfo decimalNumber = new NumberFormatInfo();
decimalNumber.NumberDecimalSeparator = ",";
decimalNumber.NumberGroupSeparator = ".";
Decimal.TryParse(vrednost, NumberStyles.Number, decimalNumber, out LastValue);
Your row.SelectSingleNode("td[2]").InnerText is a string and you are trying to format it like a decimal.
Try parsing it directly:
decimal LastValue;
string vrednost = row.SelectSingleNode("td[2]").InnerText;
if (Decimal.TryParse(vrednost, out LastValue))
Check your cultureinfo at first and set it appropriately.
CultureInfo MyUsersCulture = Thread.CurrentThread.CurrentCulture;
Console.WriteLine("The culture: "+ MyUsersCulture.Name);
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
ConsoleWriteLine("The culture: " + Thread.CurrentThread.CurrentCulture);

Categories

Resources