Is there any way to format a number in the currency format (in the current Culture) using a custom format string?
For example:
1525.00 -> $1,525 (no trailing zeros)
1525.25 -> $1,525.25 (show decimals only when necessary)
We have tried different formats but none of them can produce the above.
As far as I know, no, you can't do that with a "one" format since you don't want show decimal parts for the first one but you "want" to show decimals part for the second one. I don't think there will be a "simple" format for both.
You can check the Currency format specifier (C) for that as;
var v = 1525.00;
$"{v:C0}".Dump();
returns $1,525 and
var v = 1525.25;
$"{v:C2}".Dump();
return $1,525.25.
Just a note, string interpolation uses CurrentCulture settings and in that case, I assume your current culture is somewhat based on english-based or InvariantCulture for generate CurrencySymbol, NumberGroupSeparator and NumberDecimalSeparator as $, , and . respectively.
Does this count?
static string MyCustomCurrencyString(decimal d) => d % 1 == 0 ? $"{d:C0}" : $"{d:C2}";
Let's test it:
Console.WriteLine(ZerosAreBad(1525));
Console.WriteLine(ZerosAreBad(1525.25m));
It works!
$1,525
$1,525.25
Related
I have a string totalPRice which holds a value like this 1147,5
I want two things.
1)round the value so that there is always two digits after ,
2)Implement thousands separator in this string, So that final out put will be some thing like this 1.147,50
I have tried some thing like this
String.Format("{0:0.00}", totalPRice)
It does my first requirement correctly by producing an output 1147,50.
But I am way behind in my second requirement. Can any one tell me how I can achieve this?
Note: In danish culture . stands for , and , stands for .
You can refer to Standard Numeric Format Strings and use
string.Format("{0:N2}", 1234.56)
You may also specify the culture manually, if danish is not your default culture:
var danishCulture = CultureInfo.CreateSpecificCulture("da-DK");
string.Format(danishCulture, "{0:N2}", 1234.56);
see MSDN Reference for CultureInfo
You should create a culture-specific CultureInfo object and use it when converting the number into a string. Also, you can set the default culture for your whole program.
Then, your code will look like this:
// create Dennmark-specific culture settings
CultureInfo danishCulture = new CultureInfo("da");
// format the number so that correct Danish decimal and group separators are used
decimal totalPrice = 1234.5m;
Console.WriteLine(totalPrice.ToString("#,###.##", danishCulture));
Note that . and , in the formatting string are specified opposit as you want. This is because they identify decimal and group separators, and are replaced with the correct culture specific-ones.
Try this:
String.Format("{0:N2}", totalPRice)
Another possibility is to use the ToString(string format) overload.
totalPRice.ToString("N2");
If this is a currency value (money!), then it's better to use the current format specifier 'C' or 'c':
string.Format("{0:C}", 1234.56)
Normally I don't write the number of decimal digits since it comes from the international configuration.
You may way to use a different colture specifier if you don't want to use the default one.
var colture = CultureInfo.CreateSpecificCulture("§§§§§");
string.Format(culture, "{0:C}", 1234.56);
where §§§§§ is the string that identifies the desired colture.
Try this for Price format. Put it under template field instead of BoundField.
<%#(decimal.Parse(Eval("YourDataField").ToString())).ToString("N2")%>
I am passing a double across a network,
currently I do
double value = 0.25;
string networkMsg = "command " + value;
the networkMsg is fine in english where its 0.25 and french where its 0,25, but when i go from a french computer to an english computer one side is making it 0.25 and the other is trying to read 0,25.
So i can to use region invariant methods in my code.
I have found Val(networkMsg) that will always read 0.25 no matter the region.
but I cannot find a guaranteed way of converting from value to 0.25 region invariant.
would value.toString("0.0") work?
Use:
string networkMsg = "command " + value.ToString(CultureInfo.InvariantCulture);
or:
string networkMsg = string.Format(CultureInfo.InvariantCulture, "command {0}", value);
This needs using System.Globalization; in the top of your file.
Note: If you need full precision, so that you can restore the exact double again, use the Format solution with the roundtrip format {0:R}, instead of just {0}. You can use other format strings, for example {0:N4} will insert thousands separators and round to four dicimals (four digits after the decimal point).
Since C# 6.0 (2015), you can now use:
string networkMsg = FormattableString.Invariant($"command {value}");
The . in the format specifier "0.0" doesn't actually mean "dot" - it means "decimal separator" - which is , in France and several other European cultures. You probably want:
value.ToString(CultureInfo.InvariantCulture)
or
value.ToString("0.0", CultureInfo.InvariantCulture)
For info, you can see this (and many other things) by inspecting the fr culture:
var decimalSeparator = CultureInfo.GetCultureInfo("fr")
.NumberFormat.NumberDecimalSeparator;
Specify the invariant culture as the format provider:
value.ToString(CultureInfo.InvariantCulture);
When I try to convert a string to a numeric value with Parse or TryParse or Convert.ChangeType, I can't manage de thousand separator as it is defined in the system:
if I enter :
var d = double.Parse("1,234", CultureInfo.CurrentUICulture);
it does not return 1234.
If I want to use the group separator, I must type :
var d = double.Parse("1,234", NumberStyles.Number, CultureInfo.CurrentUICulture);
This time, the result is that one expected.
But, I don't want to force the use of the thousand separator, I want use it only if the system specify it in the globalization settings. Is there a way to know if the separator is used (I know that I can read the group separator in CultureInfo.CurrentUICulture.NumberFormat.NumberGroupSeparator)
Cheers
Loic
Having Number (which includes AllowThousands) doesn't demand a comma - it simply allows it. So you could use Number with or without the comma. Or use Any or AllowThousands.
Note that "comma" is swappable with "thousands separator" - i.e. in some of Eurupe it may vary (period etc). If you mean "comma is thousands" then use a fixed culture (such as InvariantCulture).
You could always use the second line you use
var d = double.Parse("1,234", NumberStyles.Number, CultureInfo.CurrentUICulture);
as it will correctly convert 1234 as well as 1,234 and it should cover 1.234 on systems that use '.' as the group separator
You should parse user input using CurrentCulture and not CurrentUICulture.
The property CurrentUICulture refers to the language on which the user interface is displayed and CurrentCulture to the current locale specified in Windows. This way a user working with an application that provides a user interface translated to english (CurrentUICulture) can still view/enter, for example, dates and numbers formatted as the locale that he set in Windows (CurrentCulture).
I have these numbers:
5.25
10251.35
5
and I want them to be formatted with groups and always with 2 decimals ,XX
this is what .ToString("N2") does:
5,25
10.251,35
5
How can i make the '5' look like 5,00 too ?
And for multiple cultures of course (en: 5.0, de: 5,0 ...)
In fact this question has no sense, N2 should do it at all costs. The problem was in my WebServer.
Isn't this working for you:
decimal d = 5m;
string formatted = d.ToString("N2");
This will use the current culture, but you could specify one:
string formatted = d.ToString("N2", new CultureInfo("fr-FR"));
.ToString("{0:#,0.00}")
Note: although this uses US grouping & decimal symbols, the result will be locale aware, assuming that either your current user locale is set correctly or you pass a locale into ToString().
IIRC:
toString("0:0.00");
MSDN
With the format you have (Fixed-point), you should use:
.ToString("F2");
You have all the format here: MSDN
This is driving me crazy. I have the following string in a ASP.NET 2.0 WebForm Page
string s = "0.009";
Simple enough. Now, if my culture is Spanish - which is "es-ES" - and I try to convert the string to Double, I do the following:
double d = Double.Parse(s, new CultureInfo("es-ES"));
what I'd expect is 0,009. Instead, I get 9. I understand that .NET thinks it is a thousand separator, which in en-US is a comma, but shouldn't it take the culture info I'm passing to the parse method and apply the correct format to the conversion?
If I do
double d = 0.009D;
string formatted = d.ToString(new CultureInfo("es-ES"));
formatted is now 0,009. Anybody?
It is taking the culture you gave and applying the correct formatting. You provided a string of "0.009" and told it that it was Spanish...then you complain that it properly interpreted it as Spanish! Don't tell it that the string is Spanish when you know it isn't.
You should pass the Parse method the culture of the string being parsed, which in this case would be en-US or en-Gb or InvariantCulture.
what Jess's writing works for me. just for anyone who'd need to try out how to get "invariant culture": it looks this
double d = Double.Parse(myString, CultureInfo.InvariantCulture);
(first stackoverflow post, so yea, rather marginal ;)
You have it backwards.
When you say double d = Double.Parse(s, new CultureInfo("es-ES"));, you are asking .NET to parse your string into a double, assuming that the string is written in the es-ES culture.
In Spanish culture, "." is a thousands separator, so "0.009" is 9.
When you convert using ToString(), at the end, it's saying convert 0.009 to a string using the spanish culture, so it uses "," as the decimal separator, and you get "0,009". The behavior is correct.
My guess is that you want to use Double.Parse with the Invariant Culture, and ToString with the spanish culture, so 0.009 becomes 0,009.
I think you are interpreting it the wrong way around, in es-ES culture 0.009 is really just a long way of saying 9, as the "." is not the decimal separator, so if you ask for the string "0.009" to be parsed with the es-ES culture you should indeed get the deouble 9.0. If you ask it to parse "0,009" you should get a double of 0.009.
Similarly, if you ask it to format the double 0.009 you should get the string "0,009" in es-ES.
You're mistaking parsing and formatting. You get 9 instead of .009 the first time because you take a string that is formated in a .-based culture and parse it using a ,-based culture. You need to parse it using whatever culture it was created with and then format it using whatever culture you want for display.
double d = Double.Parse("0,009",
NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands,
CultureInfo.CreateSpecificCulture("es-ES"));
In es-ES culture "," is a decimal seporator (not ".")