c# decimal.toString() conversion problem
Example: I have a value in decimal(.1)
when I convert decimal to string using toString() it returns (0,10). Instead of .(DOT) it returns ,(COMMA).
I believe this is to do with the culture/region which your operating system is set to. You can fix/change the way the string is parsed by adding in a format overload in the .ToString() method.
For example
decimalValue.ToString(CultureInfo.InvariantCulture);
you have to define the format, it will depend in your local setting or
define the format, using something like this
decimal.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
cheers
For this to be happening, the thread's current culture must be one that uses a separator of comma instead of dot.
You can change this on a per ToString basis using the overload for ToString that takes a culture:
var withDot = myVal.ToString(CultureInfo.InvariantCulture);
Alternatively, you can change this for the whole thread by setting the thread's culture before performing any calls to ToString():
var ci = CultureInfo.InvariantCulture;
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
var first = myVal.ToString();
var second = anotherVal.ToString();
For comma (,)
try this:
decimalValue.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("tr-tr"))
Then your current culture's NumberDecimalSeparator is , instead of ..
If that's not desired you can force the dot with CultureInfo.InvariantCulture:
decimal num = 0.1m;
string numWithDotAsSeparator = num.ToString(CultureInfo.InvariantCulture);
or NumberFormatInfo.InvariantInfo
string numWithDotAsSeparator = num.ToString(NumberFormatInfo.InvariantInfo)
Related
I am working with doubles. In the Netherlands we make use of 51,3 instead of 51.3. I did write a piece of code that works with dots instead of commas. But the result of the previously written code returns a double the English way, with a dot. I am encountering some strange errors.
Here is what I have:
var calResult = 15.2d;
var calResultString = calResult.ToString(CultureInfo.GetCultureInfo("nl-NL"));
var result = double.Parse(calResultString);
calResult == "15.2" -> as expected
calResultString == "15,2" -> as expected
result == "152" -> here I expect a comma.
A also did try to add the cultureinfo also in the double.Parse. This resulted in a "15.2".
TLDR: I need to convert an English/American double to a Dutch(or similar rules) one.
Thanks in advance! :)
P.S
I hope this is not a duplicate question, but didn't found anything this specific.
You, probably, should either provide "nl-NL" whenever you work with Netherlands' culture
var calResult = 15.2d;
var calResultString = calResult.ToString(CultureInfo.GetCultureInfo("nl-NL"));
// We should parse with "nl-NL", not with CurrentCulture which seems to be "en-US"
var result = double.Parse(calResultString, CultureInfo.GetCultureInfo("nl-NL"));
Or specify CurrentCulture (default culture)
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("nl-NL");
var calResult = 15.2d;
// now CultureInfo.GetCultureInfo("nl-NL") is redundant
var calResultString = calResult.ToString();
var result = double.Parse(calResultString);
Finally, if you have a string which represents some floating point value in en-US culture, and you want the same value but be a string in nl-NL format:
string source = "123.456";
string result = double
.Parse(source, CultureInfo.GetCultureInfo("en-US"))
.ToString(CultureInfo.GetCultureInfo("nl-NL"));
Numbers and strings don't contain any culture information, instead you specify the culture when you convert between numbers and strings.
result == "152" -> here I expect a comma
What happened is that you asked the operating system to parse "15,2" into a double, and didn't specify a culture. It defaulted to US culture and ignored the comma.
If you'd specified a culture:
var result = double.Parse(calResultString, CultureInfo.GetCultureInfo("nl-NL"));
it would have given you the right value (15.2), and that might even have been displayed as 15,2 if your computer was configured to the right number format (and the debugger used your preference).
Ideally you don't hard-code the culture, but use the culture that the user has chosen.
I've written a simple method that will check for the coma character in your input and replace it with a dot. I believe the best way is to take an input as a string value. this way you can manipulate it and then you can parse it and return a double or a string if you wish:
var input = Console.ReadLine();
double parsedDouble;
if (input.Contains(","))
{
input = input.ToString().Replace(",", ".");
}
if (!Double.TryParse(input, out parsedDouble))
{
Console.WriteLine("Error parsing input");
}
else
{
Console.WriteLine(parsedDouble);
}
Console.ReadLine();
edit: the answers from Robin Bennett/Dmitry Bychenko are much better than mine, as mine is just more manual. I wasn't aware of the overload of parse that he had provided.
I'll leave my solution, cause it does solve this issue, even if it's a bit more... brute ;)
var calResult = 15.2d;
var calResultString = calResult.ToString();
string result = double.Parse(calResultString).ToString(CultureInfo.GetCultureInfo("nl-NL"));
I try find this in Windows.Globalization, but didn't find.
Is it possible to get it or not? If not? Are there alternative ways of formatting in different regions?
Example: Convert.ToDouble("0" + Decimal_Symbol.ToString() + "0001");
It's in System.Globalization, not Windows.Globalization:
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
you will find above an example of how to use the french culture, after according to your need you can change the culture.
decimal decimalNumber = 1000.1m;
var culture = CultureInfo.GetCultureInfo("fr-fr");
Console.WriteLine(decimalNumber.ToString(culture));
You can try to use CultureInfo, and the ToString overload that asks number formatting.
In this example, N4 is a number displayed with 4 decimals:
var MyNumber = 123.4567m;
var MyCulture = new System.Globalization.CultureInfo("pt-BR"); // en-US fr-FR
var Result = MyNumber.ToString("N4", MyCulture);
char regionSymbol = (1.1).ToString()[1];
I need to keep culture when converting double to string and also round to only one decimal place.
Converting double to string with culture:
((12275454.8).ToString("N", new CultureInfo("sl-SI")));
Gives output:
12.275.454,80
Converting double to string with only one decimal:
string.Format("{0:F1}",12275454.8)
Gives output:
12275454.8
The second output is without culture, the first output is not rounded to one decimal place. How to combine both methods?
Just use the format string of your second example in your first example, i.e.:
((12275454.8).ToString("N1", new CultureInfo("sl-SI")));
Edit: Changed format from F1 to N1 as per request. The difference between both is that N additionally uses thousands separators, whereas F does not. For details see https://msdn.microsoft.com/en-US/library/dwhawy9k(v=vs.110).aspx
You can set "sl-SI" culture as a default one:
using System.Threading;
...
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("sl-SI");
string test = string.Format("{0:F1}",12275454.8);
Add try..finally if you want "sl-SI" culture for a block of code only:
var savedCulture = Thread.CurrentThread.CurrentCulture;
try {
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("sl-SI");
// Let's work with "sl-SI" for a while
string test = string.Format("{0:F1}",12275454.8);
...
}
finally {
Thread.CurrentThread.CurrentCulture = savedCulture;
}
I have a variable of type Long i.e.
long quantity=1000;
I want to display it like 1,000 in Grid (Must need commas)
How do i achieve this?
I am using a Telerik Grid and I am binding the data as follows:
columns.Bound(tempProductList => tempProductList.tempProductListQuantity) .Title("Quantity")
Here you have a list of all the standard numeric formats. I think "N" is the one you want.
long l = 1234;
string s = l.ToString("N0"); //gives "1,234"
The "0" after the format specifier is the number of desired decimal places (usually 2 by default).
Note that this version is culture-sensitive, i.e., in my country, we use dots (".") as thousand separators, so the actual returned value will be "1.234" instead of the "1,234". If this is desired behaviour, just leave it as is, but if you need to use commas always, then you should specify a culture as a parameter to the ToString method, like
l.ToString("N0", CultureInfo.InvariantCulture); //always return "1,234"
You could create a Custom Culture that will allow you to specify the thousand separator.
From this article:
//Create first the format provider the String.Format
//will use to format our string
CultureInfo cultureToUse = new CultureInfo("fi-FI");
Console.WriteLine("Using the following CultureInfor " +
cultureToUse.Name);
//Now practice some decimal numbers
//Here we override the culture specific formattings
cultureToUse.NumberFormat.CurrencyDecimalDigits = 3;
cultureToUse.NumberFormat.NumberDecimalDigits = 3;
cultureToUse.NumberFormat.NumberGroupSeparator = " ";
cultureToUse.NumberFormat.CurrencySymbol = "euro";
cultureToUse.NumberFormat.NumberDecimalSeparator = ",";
Next you would need to use this culture when formatting the numbers.
You could do the formattin gby hand but you could also assign the culture to the Current(UI)Culture property of the current thread.
If you want to consider the international point of view, there will not be always commas before the decimal part. ToString function will give you what you want.
(1000.0).ToString("N",new CultureInfo("en-US")) = 1,000.00
(1000.0).ToString("N",new CultureInfo("is-IS")) = 1.000,00
I have this:
var pl = new CultureInfo("pl-PL");
decimal valsue = decimal.Parse("2,25 PLN", pl);
It works ok if i don't put "PLN" into my string. But PLN is currency in my country and i think that it should parse, so maybe i am doing something wrong? Is there any option to parse this into decimal with "PLN" attached to the string?
If you take a look at your CultureInfo's NumberFormat object, this will yield some clues about how it intends to parse values. In particular, NumberFormat.CurrencySymbol for the "pl-PL" culture is zł.
In other words, this expression would parse successfully: decimal.Parse("2,25 zł", pl);
If you prefer to use PLN as the currency symbol (technically, it's the currency code), it is possible to configure a custom NumberFormat, like so:
var pln = (NumberFormatInfo) pl.NumberFormat.Clone(); // Clone is needed to create a copy whose properties can be set.
pln.CurrencySymbol = "PLN";
decimal valsue = decimal.Parse("2,25 PLN", NumberStyles.Currency, pln);
But note the usage of NumberStyles.Currency in the Parse call: by default, decimal.Parse accepts only strings containing numeric values, without currency formatting.