Double to string with culture and only one decimal place - c#

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

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)

C# - Replacing "." to "," in double value

I have to read a .txt and display it. The double values in the data are written with a ".". When I have german language enabled it doesn't interpret it as a comma. Now I tried to check if the language is set to German and replace all the "." with a ",". The values are stored in an array named "_value" but it doesn't work. Here is the code:
if ((System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName) == "de")
{
for (int i = 0; i < _value.Length; i++)
{
String temp_var = Convert.ToString(_value[i]);
temp_var.Replace(".", ",");
_value[i] = Convert.ToDouble(temp_var);
}
}
Instead of checking the language, you can also supply the culture with which the conversion is done:
// Convert string to double from the invariant culture, which treats "." as decimal:
double d = Convert.ToDouble(_value[i], CultureInfo.InvariantCulture);
// Convert double to string using the current culture, which may happen to be German and uses a ",":
string s = Convert.ToString(d);
// Or convert double to string using the specific German culture:
string s = Convert.ToString(d, new CultureInfo("de-DE"));
What I don't understand is that apparently the _value array is already a double[] - so these changes will have to be made earlier in your code, where the conversion from string to double actually happens.
Any reason you don't just set the appropriate culture temporarily?
using System.Threading;
using System.Globalization;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

Changing the number of integers on a output value after the decimal point

So I'm learning and practicing WP7 application development.
I'm working with integers (currency), and it seems to always display four integers after the decimal place. I'm trying to cut it down to just either ONE or TWO decimal places.
I've been trying to use the "my variable.ToString("C2")" (C for Currency, 2 for number of ints after the decimal)
I'm probably missing something obvious, but please help
decimal number = new decimal(1000.12345678);
string text = number.ToString("#.##");
Output:
1000,12
An other way:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencyDecimalDigits = 2;
decimal val = new decimal(1000.12345678);
string text = val.ToString("c", nfi);
When formatting a currency, NumberFormatInfo allows specifying following properties as well:
CurrencyDecimalDigits
CurrencyDecimalSeparator
CurrencyGroupSeparator
CurrencyGroupSizes
CurrencyNegativePattern
CurrencyPositivePattern
CurrencySymbol
See Custom Numeric Format Strings on MSDN for more examples
The "C" format string defines the currency specifier as described on MSDN. This will include the currency symbol for the current culture, or for a specific culture if supplied, e.g.
double amount = 1234.5678;
string formatted = amount.ToString("C", CultureInfo.CreateSpecificCulture("en-US"));
// This gives $1234.56
In your case, it seems that you have a limited set of currency symbols that you support, so I would suggest using the fixed point format specifier "F" instead. By default this will give you 2 decimal points, but you can specify a number to vary this, e.g.
double amount = 1234.5678;
string formatted = amount.ToString("F");
// This gives 1234.56
formatted = amount.ToString("F3");
// This gives 1234.567
Using the fixed point specifier will give you control over the number of decimal points and enable you to concatenate the currency symbol.
The only thing I would add to "sll" answer is to pay attention on Culture (they often forget to mantion this), like this (example)
string text = val.ToString("#.##", CultureInfo.InvariantCulture);
double total = 526.4134
string moneyValue = total.ToString("c");
This will display it in this format: $#.##

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(".", ","));
}
}

Categories

Resources