How take decimal symbol (string/char) in current region? - c#

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];

Related

Parsing double with dot to comma

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"));

c# decimal toString() conversion with comma(,)

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)

Convert string to decimal with format

I need convert a String to a decimal in C#, but this string have different formats.
For example:
"50085"
"500,85"
"500.85"
This should be convert for 500,85 in decimal. Is there is a simplified form to do this convertion using format?
Some cultures use a comma to indicate the floating point. You can test this with the following code on an aspx page:
var x = decimal.Parse("500,85");
Response.Write(x + (decimal)0.15);
This gives the answer 501 when the thread culture has been set to a culture that uses the comma as floating point. You can force this like so:
var x = decimal.Parse("500,85", new NumberFormatInfo() { NumberDecimalSeparator = "," });
While decimal.Parse() is the method you are looking for, you will have to provide a bit more information to it. It will not automatically pick between the 3 formats you give, you will have to tell it which format you are expecting (in the form of an IFormatProvider). Note that even with an IFormatProvider, I don't think "50085" will be properly pulled in.
The only consistent thing I see is that it appears from your examples that you always expect two decimal places of precision. If that is the case, you could strip out all periods and commas and then divide by 100.
Maybe something like:
public decimal? CustomParse(string incomingValue)
{
decimal val;
if (!decimal.TryParse(incomingValue.Replace(",", "").Replace(".", ""), NumberStyles.Number, CultureInfo.InvariantCulture, out val))
return null;
return val / 100;
}
This will work, depending on your culture settings:
string s = "500.85";
decimal d = decimal.Parse(s);
If your culture does not by default allow , instead of . as a decimal point, you will probably need to:
s = s.Replace(',','.');
But will need to check for multiple .'s... this seems to boil down to more of an issue of input sanitization. If you are able to validate and sanitize the input to all conform to a set of rules, the conversion to decimal will be a lot easier.
Try this code below:
string numValue = "500,85";
System.Globalization.CultureInfo culInfo = new System.Globalization.CultureInfo("fr-FR");
decimal decValue;
bool decValid = decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat, out decValue);
if (decValid)
{
lblDecNum.Text = Convert.ToString(decValue, culInfo.NumberFormat);
}
Since I am giving a value of 500,85 I will assume that the culture is French and hence the decimal separator is ",". Then decimal.TryParse(numValue, System.Globalization.NumberStyles.Number, culInfo.NumberFormat,out decValue);
will return the value as 500.85 in decValue. Similarly if the user is English US then change the culInfo constructor.
There are numerous ways:
System.Convert.ToDecimal("232.23")
Double.Parse("232.23")
double test;
Double.TryParse("232.23", out test)
Make sure you try and catch...
This is a new feature called Digit Grouping Symbol.
Steps:
Open Region and Language in control panel
Click on Additional setting
On Numbers tab
Set Digit Grouping Symbol as custom setting.
Change comma; replace with (any character as A to Z or {/,}).
Digit Grouping Symbol=e;
Example:
string checkFormate = "123e123";
decimal outPut = 0.0M;
decimal.TryParse(checkFormate, out outPut);
Ans: outPut=123123;
Try This
public decimal AutoParse(string value)
{
if (Convert.ToDecimal("3.3") == ((decimal)3.3))
{
return Convert.ToDecimal(value.Replace(",", "."));
}
else
{
return Convert.ToDecimal(value.Replace(".", ","));
}
}

Replace dot(.) with comma(,) using RegEx?

I am working on a C# application. I want to change number decimal figure with comma(,) where i have dot(.) using regular expression.
For example:
Price= 100,00.56
As this international rule of representing numeric values but I Sweden they have different ways for numbers Like
Price= 100.00,56
So i want to change dot(.) into comma(,) and comma(,) into dot(.) using RegEx. Could guide me about this.
When formatting numbers, you should use the string format overload that takes a CultureInfo object. The culture name for swedish is "sv-SE", as can be seen here.
decimal value = -16325.62m;
Console.WriteLine(value.ToString(CultureInfo.CreateSpecificCulture("sv-SE")));
Edit:
As #OregonGhost points out - parsing out numbers should also be done with CultureInfo.
Not a RegEx solution but from my experience - more correct:
public static string CheckDecimalDigitsDelimiter(this string instance)
{
var sv = new CultureInfo("sv-SE");
var en = new CultureInfo("en-US");
decimal d;
return (!Decimal.TryParse(instance, NumberStyles.Currency, sv, out d) &&
Decimal.TryParse(instance, NumberStyles.Currency, en, out d)) ?
d.ToString(sv) : // didn't passed by SV but did by EN
instance;
}
What does this method do? It ensures that if given string is incorrect Sweden string but is correct English - convert it to Sweden, e.g. 100,00 -> 100,00 but 100.00 -> 100,00.
You can do this even without regex. For example
var temp = price.Replace(".", "<TEMP>");
var temp2 = temp.Replace(",", ".");
var replaced = temp2.Replace("<TEMP>", ",");
Also have a look at
System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
Not sure what 100,00.56 represents, did you mean 10.000,56?
To answer your question:
For such a simple task, why use RegEx? You can do it much easier:
string oldValue = "100,00.56";
char dummyChar = '&'; //here put a char that you know won't appear in the strings
var newValue = oldValue.Replace('.', dummyChar)
.Replace(',', '.')
.Replace(dummyChar, ',');
Edit
I agree with #Oded, for formatting numbers use the CultureInfo class.
Do not rely on RegExp for this kind of thing :) Use the build in cultures fx:
decimal s = decimal.Parse("10,000.56", NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"));
string output = s.ToString("N",CultureInfo.GetCultureInfo("da-DK"));
en-US will parse it correctly and da-DK uses the other kind of representation. I live in DK and therefore use that but you should use the culture which fits your output.

Custom Currency symbol and decimal places using decimal.ToString("C") and CultureInfo

I have a problem with decimal.ToString("C") override.
Basically what I wants to do is as follows:
CultureInfo usCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = usCulture;
NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
LocalFormat.CurrencySymbol = "RM";
I wants to make above code a function (override ToString("C")) whereby when the following code get executed:
decimal paid = Convert.ToDecimal(dr["TotalPaids"]);
lblPaids.Text = paid.ToString("C");
The results would be RM4,900.00 instead of $4,900.00
How do I create an override for decimal.ToString("C") that would solve my problem
Thanks in advance.
To get a format like RM 11,123,456.00 you also need to set the following properties
CurrentCulture modified = new CultureInfo(Thread.CurrentThread.CurrentCulture.Name);
Thread.CurrentThread.CurrentCulture = modified;
var numberFormat = modified.NumberFormat;
numberFormat.CurrencySymbol = "RM";
numberFormat.CurrencyDecimalDigits = 2;
numberFormat.CurrencyDecimalSeparator = ".";
numberFormat.CurrencyGroupSeparator = ",";
If you do that at application startup then that should make ms-MY format like en-US but with the RM currency symbol every time you call the ToString("C") method.
If I understand your question correctly what you want is to replace the $ with RM. If so, you need to pass the custom format...
lblPaids.Text = paid.ToString("C", LocalFormat);
use this format string :
#,##0.00 $;#,##0.00'- $';0 $
decimal paid = Convert.ToDecimal(dr["TotalPaids"]);
lblPaids.Text = paid.ToString("#,##0.00 $;#,##0.00'- $';0 $");
You can use the Double.ToString Method (String, IFormatProvider) https://msdn.microsoft.com/en-us/library/d8ztz0sa(v=vs.110).aspx
double amount = 1234.95;
amount.ToString("C") // whatever the executing computer thinks is the right fomat
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ie")) // €1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("es-es")) // 1.234,95 €
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-GB")) // £1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-au")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-us")) // $1,234.95
amount.ToString("C", System.Globalization.CultureInfo.GetCultureInfo("en-ca")) // $1,234.95
lblPaids.Text = paid.ToString("C",usCulture.Name);
Or
lblPaids.Text = paid.ToString("C",LocalFormat.Name);
must Work

Categories

Resources