Globalization .net convert string to double - c#

İ 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

Related

C# - invariant culture

I'm trying to convert a double to a decimal with a dot instead of a comma. I feel like I have tried every single possible way (except a working one) so I'm out of ideas.
double amount = myUsd / price;
string amountAsString = amount.ToString();
decimal value = Decimal.Parse(amountAsString, CultureInfo.InvariantCulture);
This one gives a FormatException for example.
Thanks
As Hans Passant said, if you Parse in the same way as you Format you'll avoid a lot of issues -> Use string amountAsString = amount.ToString(CultureInfo.InvariantCulture);
EDIT
Since you're passing in an exponential notation you need to tell the Parser this. This worked with your example value:
decimal value = Decimal.Parse(amountAsString, System.Globalization.NumberStyles.Float, CultureInfo.InvariantCulture);
But I suggest NOT formatting it as a Double. First convert it to a Decimal. Then parse it as a Decimal:
double amount = myUsd / price;
Decimal decAmount = (Decimal)amount;
string amountAsString = decAmount.ToString(CultureInfo.InvariantCulture);
decimal value = Decimal.Parse(amountAsString, CultureInfo.InvariantCulture);
Then it'll never get formatted in exponential notation.
Also see this C# Fiddle snippet

C# how to parse a string to double [duplicate]

This question already has answers here:
How do I parse a string with a decimal point to a double?
(19 answers)
Closed 6 years ago.
I want to parse my string to double. My problem is that the result of newTime is 800, but the result should be 8,00.
string time = "08:00";
double newTime = double.Parse(time.Replace(':', '.'));
If you want to treat : as a decimal separator, just do it:
string time = "08:00";
// when parsing "time", decimal separator is ":"
double newTime = double.Parse(time,
new NumberFormatInfo() { NumberDecimalSeparator = ":" });
Try avoiding tricks with magic constants like '.' in the time.Replace(':', '.'). Please, notice that newTime will be 8, not 8.00 (since 8 == 8.0 == 8.00 == 8.000...). If you want to represent newTime with two digits after the decimal point use formatting:
// F2 - format string ensures 2 digits after the decimal point
// Outcome: 8.00
Console.Write(newTime.ToString("F2"));
The result of Double.Parse is a Double, not a string. You need to output a string from the double, using ToString.
You should also use an overload of Double.Parse that has a NumberStyles parameter. Using the Float value allows exponent notation.
string time = "08:00";
double newTime = double.Parse(time.Replace(':', '.'), CultureInfo.InvariantCulture);
Your issue is that your culture has a different decimal separator to what you are creating in your string.
You can change it to to this
string time = "08:00";
double newTime = double.Parse(time.Replace(":", Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator) );

C# convert string to double in locale

In my locale the decimal separator is a ','.
However I would still like to write a C# application which works with numbers that use the '.' as decimal separator.
string b = "0,5";
double db = double.Parse(b); // gives 0.5
string a = "0.5";
double da = double.Parse(a); // gives 5, however i would like to get 0.5
You need to specify the culture as the second argument to double.Parse, e.g.
double da = double.Parse(a, CultureInfo.InvariantCulture);
Pretty much all of the formatting/parsing methods have overloads taking an IFormatProvider, and the most commonly-specified implementation of IFormatProvider is CultureInfo.

converting string to decimal in 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);

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

Categories

Resources