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.
Related
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
If I wanted to convert a double to a string and back to a double that matches exactly, I would use something like:
double d1 = 1 / 3.0;
string s = d1.ToString("R");
double d2 = double.Parse(s);
But, the "R" format isn't defined for a decimal type (you get a "FormatException: Format specifier was invalid").
What is the way to produce a round-trip string for a decimal type?
The default output format for decimal round-trips, so you don't have to do anything special. It is just like int in that sense.
Decimal is in fact a binary-decimal value (it uses base of 10, not 2 as in Double) and that's why there's no need to special exact representations like ToString("R");
Decimal value = 123.456m;
String result = value.ToString(CultureInfo.InvariantCulture); // <- That's enough
See also for details:
http://csharpindepth.com/articles/general/decimal.aspx
If you try,
decimal d1 = 1m / 3;
string s = d1.ToString();
decimal d2 = decimal.Parse(s);
// where d1 == d2 = true
You will see you do not need any extra formatting options to obtain a proper string representation.
İ 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
I have many decimals, each rounded differently:
decimal quantity = Decimal.Round(item.Quantity.Value, 2,
MidpointRounding.AwayFromZero);
decimal difference = Decimal.Round(quantity * eva, 0,
MidpointRounding.AwayFromZero);
When binding to the UI, I convert to string like this:
string Quantity = quantity.ToString("G", CultureInfo.InvariantCulture);
string Difference = difference.ToString("G", CultureInfo.InvariantCulture);
Is there a generic way to insert commas for thousand separators while keeping the original decimal rounding the same?
Try using Format.
double d = 1.234567;
String output = d.ToString("#,##0.##");
Also,
double d = 123456789.1;
string format = d.ToString().
IndexOf(NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)
>=0 ? "#,##0.00" : "#,##0";
Console.WriteLine (d.ToString(format));
For anyone wondering, I ended up using String.Format(new CultureInfo("en-US"), "{0:N}", difference) and changed the N depending on how many decimal places I needed.
You can use the "N" format specifier and supply the number of digits you want any number to retain. If you want each number to potentially have a different number of digits you wall have to determine the number to supply to the format string each time.
quantity.ToString("N(digits)");
Complete documentation is at http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#NFormatString
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