I'm having issues with currency formatting in C#.
I'm using framework 2.0.
When I use this code:
CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";
price.Value.ToString("C", numberFormatInfo) seems to give me a string with a white space between amount and currency. That's horrible! I absolutely need a no-break space!
What is going on? Am I missing a format property or is it the C# standard?
Thanks for your help!
So basically you want price.Value.ToString("C", numberFormatInfo).Replace(' ', '\u00A0');? At least that should be the code for non breaking space. – Corak
Exactly the same as above commentor, but using the asci-values instead; > price.Value.ToString("C", numberFormatInfo).Replace((char) 32, (char) 160); (160 is a lot > easier to remember, atleast for me :)) – flindeberg
Adding an answer based on my interpretation of the question, which #Corak seems to share.
// Convert "breaking" spaces into "non-breaking" spaces (ie the html )
price.Value.ToString("C", numberFormatInfo).Replace((char) 32, (char) 160);
Doing the same with unicode (courtesy of #Corak's link):
// Convert "breaking" spaces into "non-breaking" spaces without int cast to char
price.Value.ToString("C", numberFormatInfo).Replace(' ', '\u00A0');
And btw (roslyn repl):
> '\u00A0' == (char) 160
true
And if you are going to be using it alot also get the extension method:
public static class StringExtensions
{// CurrencyType is your currency type, guessing double or decimal?
public static string ToCurrencyString(this CurrencyType value, IFormatInfo format)
{
return value.ToString("C", format).Replace((char) 32, (char) 160);
}
}
Use:
numberFormatInfo.CurrencyPositivePattern = 1;
For value 1 the format is n$ where $ is currency symbol and in your case its CHF
Formatting Types - MSDN
The CurrencyNegativePattern or CurrencyPositivePattern property, which
returns an integer that determines the following:
The placement of the currency symbol.
Whether negative values are indicated by a leading negative sign, a trailing negative sign, or parentheses.
Whether a space appears between the numeric value and the currency symbol.
Try the following code:
CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";
numberFormatInfo.CurrencyPositivePattern = 1;
decimal d = 123.23M;
var temp = d.ToString("C", numberFormatInfo);
Output:
123,23CHF
You can replace it.
price.ToString("C", numberFormatInfo).Replace(" ", "")
or better set NumberFormatInfo.CurrencyPositivePattern to 1
numberFormatInfo.CurrencySymbol = "CHF";
numberFormatInfo.CurrencyPositivePattern = 1;
Full example;
CultureInfo culture = new CultureInfo("fr-FR", false);
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencySymbol = "CHF";
numberFormatInfo.CurrencyPositivePattern = 1;
Console.WriteLine((1.5M).ToString("C", numberFormatInfo));
Output will be;
1,50CHF
Here a DEMO.
From Formatting Types
The CurrencyNegativePattern or CurrencyPositivePattern property, which
returns an integer that determines the following:
The placement of the currency symbol.
Whether negative values are indicated by a leading negative sign, a trailing negative sign, or parentheses.
Whether a space appears between the numeric value and the currency symbol.
You can configure the CurrencyPositivePattern and set it to something appropriate.
// whatever code you had
NumberFormatInfo numberFormatInfo = (NumberFormatInfo)culture.NumberFormat.Clone();
numberFormatInfo.CurrencyPositivePattern = 1; // will format like 25.00CHF
Seems like by default it includes space when it comes to other currencies than $
double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3",
CultureInfo.CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose
// current culture is English (United States):
// $12,345.68
// $12,345.679
// kr 12.345,679
if you want to replace space, you can use as Soner said,
numberString.ToString("C", numberFormatInfo).Replace(" ", "");
In your global.asax ou can globaly change the culture and chose to remove the space like this :
CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("fr-FR"); //Get you own culture
cultureInfo.NumberFormat.CurrencyPositivePattern = 1; //To remove the space
Thread.CurrentThread.CurrentUICulture = cultureInfo; //Apply globaly to your application
Thread.CurrentThread.CurrentCulture = cultureInfo; //Apply globaly to your application
The clean solution is set your CurrencyPositivePattern to 0.
Example:
CultureInfo _culture= (CultureInfo) culture.Clone();
_culture.NumberFormat.CurrencyPositivePattern = 0;
var stringFormat = number.ToString("c3", _culture);
input: 1234567.845
output: $1.234.568
output: €1.234.568
output: S/1.234.568
Related
I need to format ints and floats to string.
If it's float, I need , to be decimal separator. And . must be thousand separator.
Also, I need to complete remaining decimals with 0. Some examples:
float:
45,3: 000.045,30
125: 000.125,00
83560.195: 083.560,19
int:
45: 000.045
5789: 005.789
I managed to format thousands with "{0:#,0}" but I still can't find how to format decimals and how to properly pad keeping separators.
This must be done regardless of configured culture :/
This works with the given examples:
NumberFormatInfo numberFormat = new NumberFormatInfo
{
NumberDecimalSeparator=",",
NumberGroupSeparator="."
};
string formatFloat(float f)
{
return f.ToString("0####,0.00",numberFormat);
}
string formatInt(int i)
{
return i.ToString("0####,0",numberFormat);
}
You can set the culture to a European culture, and format:
string.Format(new CultureInfo("de-DE"), "{0:000,000.00}", num).Dump();
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: $#.##
string str = e.Row.Cells[index].Text;
int value = Int32.Parse(str, NumberStyles.AllowThousands, NumberFormatInfo.InvariantInfo);
if (value >= 100)
e.Row.Cells[index].BackColor = System.Drawing.Color.Green;
Cell values are 168,88 - 125,45 - 75,3
After parsing str returns 16888 - 12545 - 753 , so all of the cells are set as green
how can i compare real values.?
You are using NumberFormatInfo.InvariantInfo. This treats , as thousands separator.
Are you sure this is the correct one? Did you mean to use something like CultureInfo.GetCulture("fr-FR"), where the , is the decimal separator?
Additionally, if you need to preserve the decimal part, why parse to an integer?
This should work better for you:
decimal.Parse(str, NumberStyles.AllowThousands, CultureInfo.GetCulture("fr-FR"));
I think what you're looking for is:
int value = Int32.Parse(str, NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
The NumberFormatInfo tells the Parse function HOW the input should be interpreted. The InvariantInfo reads as Gets the default read-only NumberFormatInfo that is culture-independent (invariant) from msdn.
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.