I'm developing a website for a German Customer. In Germany, they use comma as decimal separator.
I use a WebMethod to get the values from SQL and then build a JSON object to show the data on the website. Using C# SqlCommand, I got the value from SQL as a string. I want to save this value into a double variable.
This is the code example which shows what I want to do:
NumberFormatInfo nfi = new CultureInfo( "de-DE", false ).NumberFormat;
nfi.NumberDecimalSeparator = ","; // Displays the value with a comma as the separator.
string value ="15.95"; //value from SQL
string valueInString = "";
double valueInDouble = 0;
valueInString = Convert.ToDouble(value.ToString()).ToString( "N", nfi );
valueInDouble = Convert.ToDouble(value.ToString()).ToString( "N", nfi ); //Error
valueInDouble = Convert.ToDouble(valueInString,nfi);
Console.WriteLine( valueInString ); // returns 15,95. But it is a string
Console.WriteLine( valueInDouble ); // returns 15.95. the comma is reverted back to dot
I need to save the data as double. How do I resolve this?
double does not contain any information about how to (visually) separate the decimal from the integral part. If you print a double without any specific culture format info, you get the standard . as a separator.
Related
So this is a bit of a picky question. I have looked around for similar questions, but couldn't find one that specifically answers my question.
I'm making a winforms app that gets data from, among other things, numeric updowns and places them in Word docvariables. The numeric updowns have a precision of 4 decimal places, because there are some prices like €0,0125 for example printing contracts. But other prices will get saved as for example €12,5000. I currently fix the numbers with 2 decimal places like this:
string value = type.GetValue().ToString().Trim(new char[] { '\'' });
//Changes commas for European standard and removes the excess zeros after the comma.
if (type.GetType().ToString().EndsWith("Decimal"))
{
string s;
string sep = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
if (sep == ".")
s = double.Parse(value).ToString("n2").Replace('.', ',');
else
s = double.Parse(value).ToString("n2");
wordDoc.Variables[type.GetName()].Value = s;
}
else
wordDoc.Variables[type.GetName()].Value = value;
But I can't seem to figure out how to detect when a decimal shouldn't get trimmed. I don't necessarily need code examples, if someone just could send me on the right track, that would be a major help.
NB: Changing the precision of the numeric up downs isn't really an option since they get created dynamically by a method.
Just use a custom format string - #,##0.00## will show a minimum of 2 d.p. and a maximum of 4 d.p.
decimal x = 12.50000m;
decimal y = 0.0125m;
string sx = x.ToString("#,##0.00##"); // "12.50"
string sy = y.ToString("#,##0.00##"); // "0.125"
If you want a comma decimal separator, then either use an appropriate CultureInfo or create a NumberFormatInfo with the correct properties:
var nfi = new NumberFormatInfo
{
NumberDecimalSeparator = ",",
NumberGroupSeparator = ".",
};
string s = 1234.56m.ToString("#,##0.00##", nfi); // "1.234,56"
Having a decimal variable 'price' and a RegionInfo variable 'region' like this:
var price = new Decimal(49.9);
var region = new RegionInfo(Thread.CurrentThread.CurrentUICulture.LCID);
I do like this:
string.Format("{0:0,0.##} {1}", price, region.CurrencySymbol);
This will return the desired price string for two of the three cultures I wish to support (Swedish and Norwegian). Although for the third culture (Danish) it will erroneously place the currency symbol after the amount.
This is an alternative approach:
string.Format("{0:c}", price);
This works for all three cultures but now my problem is that I cannot control the number of decimal values.
My question is:
How do I simultaneously control the number of decimal values and currency culture?
I am looking for something like this (which of course does not work):
string.Format("{0:c,0.##}", price);
If I understood you correctly, isn't this what you want?
var price = new Decimal(49.9);
var cultureInfo = new CultureInfo("da-DK");
//var currentCultureInfo = new CultureInfo(CultureInfo.CurrentCulture.Name);
var test = string.Format(cultureInfo, "{0:C2}", price);
You should use NumberFormat property of a culture, as it already contains information about how many decimals should be included, but you can override it if you set the CurrencyDecimalDigits property of it.
Example from MSDN:
class NumberFormatInfoSample {
public static void Main() {
// Gets a NumberFormatInfo associated with the en-US culture.
NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;
// Displays a negative value with the default number of decimal digits (2).
Int64 myInt = -1234;
Console.WriteLine( myInt.ToString( "C", nfi ) );
// Displays the same value with four decimal digits.
nfi.CurrencyDecimalDigits = 4;
Console.WriteLine( myInt.ToString( "C", nfi ) );
}
}
/*
This code produces the following output.
($1,234.00)
($1,234.0000)
*/
I get from a webservice the following strings:
12.95
or
1,200.99
Is there an option to convert these values to the following values without manipulating the string?
12,95
or
1200,99
I tried it with some Culture options but didn't get it right...
EDIT
I tried this:
//return string.Format( "{0:f2}", Convert.ToDecimal( price ) );
//return string.Format(CultureInfo.GetCultureInfo("de-de"), "{0:0}", price);
NumberFormatInfo format = new System.Globalization.NumberFormatInfo();
format.CurrencyDecimalDigits = 2;
format.CurrencyDecimalSeparator = ",";
format.CurrencyGroupSeparator = "";
return decimal.Parse(price).ToString(format);
var input = "1,200.99";
//Convert to decimal using US culture (or other culture using . as decimal separator)
decimal value = decimal.Parse(input, CultureInfo.GetCultureInfo("en-US"));
//Convert to string using DE culture (or other culture using , as decimal separator)
string output = value.ToString(CultureInfo.GetCultureInfo("de-DE"));
Console.WriteLine(output); //1200,99
What about something like this:
double number;
double.TryParse("1,200.99", NumberStyles.Any, CultureInfo.CreateSpecificCulture("en-US"), out number);
var formattedNumber = number.ToString(CultureInfo.CreateSpecificCulture("de-DE"));
Then return or write out formattedNumber (whatever you need to do).
Yes and no. First, what you have is a string, and so you cannot change the formatting of it as you're attempting to. However, to achieve what you would like, you can parse the string into a decimal value and then use the formatting options for decimals to display it in any reasonable way.
You may try for something like this:
String.Format("{0:#,###0}", 0);
or may be like this:
string str = yourNumber.Remove(",").Replace(".",",");
Close enough tronc,
Try this snippet:
String curStr = "12.95";
Decimal decVal;
var valid = Decimal.TryParse(curStr, out decVal);
if (!valid) throw new Exception("Invalid format.");
String newFormat = decVal.ToString("C", System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"));
Within the toString(...) call, you can append a number after 'C' to specify how many decimal places should follow. E.g "C3".
I have int variables, example:
int money = 1234567890;
How I can insert "." into money, and make its format like this:
1.234.567.890
You can simply do this:
var text = money.ToString("N0",
System.Globalization.CultureInfo.GetCultureInfo("de"));
The result is:
1.234.567.890
(I just picked the German culture as I knew they use . for the separator.)
You can use NumberFormatInfo.NumberGroupSeparator:
NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;
nfi.NumberGroupSeparator = ".";
Int64 myInt = 1234567890;
Console.WriteLine( myInt.ToString( "N", nfi ) );
(Link to ideone.)
To get exactly the format, use
int money = 1234567890;
money.ToString(#"#\.###\.###\.##0");
More information on custom formats here. You need to escape the dot because otherwise the first one will be interpreted as the decimal one. 0 in the end is necessary if you want to display it for zero values.
If you want a "Money' format try:
int money = 1234567890;
string moneyString = String.Format("{0:C}", money);
returns "$1,234,567,890.00"
Im not sure what money format uses '.' instead of ',' but that could just be a globalization thing.
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: $#.##