I have a code like this;
GridView1.FooterRow.Cells[11].Text = String.Format("{0:c}", sumKV)
In my computer this code gives a result like that;
But when I upload this code to my virtual machine it looks like this;
TL means Turkish Liras. But I don't want to show the currency. I just want numbers.
I also don't want to change the formating of numbers. (Like 257.579,02)
How can I only delete TL in this code?
I would use this:
var cultureWithoutCurrencySymbol =
(CultureInfo)CultureInfo.CurrentCulture.Clone();
cultureWithoutCurrencySymbol.NumberFormat.CurrencySymbol = "";
GridView1.FooterRow.Cells[11].Text =
String.Format(cultureWithoutCurrencySymbol, "{0:c}", sumKV).Trim();
Background:
This will still keep the currency formatting for the current culture, it just removes the currency symbol.
You can save this special culture somewhere, so you don't have to create it every time you need to format your values.
UPDATE:
Now it even compiles... ;-)
Added a Trim(), because there is still a space after the formated number.
Another option is to turn off the currency symbol entirely for the current thread:
private static NumberFormatInfo SetNoCurrencySymbol()
{
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
NumberFormatInfo LocalFormat = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone();
NumberFormatInfo ret = culture.NumberFormat;
LocalFormat.CurrencySymbol = "";
culture.NumberFormat = LocalFormat;
// Add the culture to the current thread
Thread.CurrentThread.CurrentCulture = culture;
return ret;
}
That way you will change less code. You can always change it back afterwards:
NumberFormatInfo origNumberFormat = SetNoCurrencySymbol();
string x = String.Format("{0:c}", 55);
CultureInfo.CurrentCulture.NumberFormat = origNumberFormat;
string y = String.Format("{0:c}", 55);
Because you are using String.Format with a format string only, sumKV is formatted according to the UI Culture actually used in your application.
GridView1.FooterRow.Cells[11].Text = String.Format("{0:c}", sumKV),
To get rid with currency symbol, use InvariantCulture in String.Format this way :
String.Format(CultureInfo.InvariantCulture, "{0:c}", sumKV);
If you don't want to show currency then don't use the currency formatting code - {0:c}.
Perhaps try something like the following:
GridView1.FooterRow.Cells[11].Text = String.Format("{0:G}", sumKV);
See this article - String.Format doubles
Related
post.Min.ToString("0.00").Replace(",", ".").Replace(".00", string.Empty)
post.Min is a double such as 12,34 or 12,00. Expected output is 12.34 or 12.
I basically want to replace the comma by a point, and cut the .00 part if any.
I am asking because I couldn't find anything, or because I don't exactly know what to search. This has an high change of being a duplicate, I simply can't find it. Please let me know.
The simplest solution would appear to be to use CultureInfo.InvariantCulture, and I reject the suggestion that this is any more complicated than using a series of replaces as you demonstrated in your question.
post.Min.ToString("0.##", CultureInfo.InvariantCulture);
# is the digit placeholder, described as the docs like this:
Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.
Try it online
If you use this in a lot of places, and that's why you want to keep it simple, you could make an extension method:
public static class MyExtensions
{
public static string ToHappyString(this double value)
{
return value.ToString("0.##", CultureInfo.InvariantCulture);
}
}
And then you just have to call .ToHappyString() wherever you use it. For example, post.Min.ToHappyString()
You can use .ToString("0.##").
like,
// Considered german culture; May be this is your current culture
CultureInfo culture = new CultureInfo("de");
double number1 = Double.Parse("12,34", culture);
double number2 = Double.Parse("12,00", culture);
Console.WriteLine(number1.ToString("0.##"));
Console.WriteLine(number2.ToString("0.##"));
Output:
12.34
12
.Net fiddle
Checkout the ToString overloads article on MSDN about examples of the N format. This is also covered in the Standard Numeric Format Strings article.
Relevant examples:
// Formatting of 1054.32179:
// N: 1,054.32
// N0: 1,054
// N1: 1,054.3
// N2: 1,054.32
// N3: 1,054.322
For the dot instead of comma to do it properly, in combination with N0 use:
System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";
System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
double.ToString("0.##") to consider decimal places only if not .00 and you can create your own Number Format without using Culture:
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";
post.Min.ToString("0.##", nfi);
Given number is 282100. I want to display above number like 282.100,00
I am using
String.Format("{0:n}", number)
but I'm getting result like this 282,100.00.
expected=282.100,00.
Is there any way to do this in C#?
If your current culture does not format the number the way you want, you have a couple of options (at least):
Use a known CultureInfo that does format the number the way you want
Create a custom NumberFormatInfo that uses the format you want
In general, I'd say the first option is better. After all, if you have a need to format the number in a specific way, chances are it's because you are doing it for some specific culture. So the best way in that case is to just get the correct CultureInfo object (i.e. by using CultureInfo.GetCultureInfo()) and use that as the IFormatProvider for the formatting.
If for some reason it's not always clear which specific CultureInfo object to get, then you can do it the second way. For example:
decimal number = 282100;
NumberFormatInfo numberFormatInfo =
(NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
numberFormatInfo.NumberDecimalSeparator = ",";
numberFormatInfo.NumberGroupSeparator = ".";
string text = string.Format(numberFormatInfo, "{0:n}", number);
This particular example allows you to start with a known formatter and then modify it per your specific needs.
Finally, if you believe your current culture should be formatting the number the way you want but it isn't doing that, then it is best to figure out why it's not doing that, rather than overriding the current culture. Usually, you want to use the default formatting for any text displayed to the user or received from the user, so that the program works correctly regardless of culture.
You can create your own number format and use that to get desired results. Something like this:
NumberFormatInfo customFormat = new NumberFormatInfo(); ;
customFormat.NumberGroupSeparator = ".";
customFormat.NumberDecimalSeparator = ",";
customFormat.NumberGroupSizes = new int[1]{3};
decimal someNumber = 123456789.123m;
string number = someNumber.ToString("N",customFormat);
You can customize the format by providing a new IFormatProvider:
var num = 282100;
// Output using a custom formatter:
Console.WriteLine(num.ToString("N",
new NumberFormatInfo{ NumberDecimalSeparator = ",", NumberGroupSeparator = "."}));
// Or if you want to save the formatted string:
var str = String.Format(new NumberFormatInfo {NumberDecimalSeparator = ",",
NumberGroupSeparator = "."}, "{0:N}", num);
Console.WriteLine(str);
I already searched for my problem but I wasn't successfully and that's the reason I'm here.
All I want to do is reading a string like "3.14" and convert it to double.
Enough said... here is my code:
using System;
namespace GlazerCalcApplication
{
class MainClass
{
public static void Main (string[] args)
{
string heightString;
double height;
heightString = Console.ReadLine();
height = Convert.ToDouble(heightString);
Console.WriteLine(height);
}
}
}
Output:
3.14
314
Press any key to continue...
Why is my double value not 3.14?
Instead of Convert.ToDouble() I also tried it with double.Parse() but I received the same behaviour. Reading strings like 3,14 is no problem.
Maybe I should also mention that I use MonoDevelop and a linux OS.
Thanks in advance.
Try specifying the culture as Invariant:
height = Convert.ToDouble(heightString,CultureInfo.InvariantCulture);
It seems the decimal seperator of your culture is comma instead of dot therefore dot is truncated after conversion.
Convert.ToDouble(string) uses Double.Parse(string, CultureInfo.CurrentCulture) method explicitly.
Here how it's implemented;
public static double ToDouble(String value) {
if (value == null)
return 0;
return Double.Parse(value, CultureInfo.CurrentCulture);
}
It is likely your CurrentCulture's NumberFormatInfo.NumberDecimalSeparator property is not . (dot). That's why you can't parse a string with . as a date seperator.
Example in LINQPad;
CultureInfo c = new CultureInfo("de-DE");
c.NumberFormat.NumberDecimalSeparator.Dump(); // Prints ,
As a solution, you can create a new reference of your CurrentCulture and assing it's NumberDecimalSeparator property to . like;
double height;
CultureInfo c = new CultureInfo("de-DE");
c.NumberFormat.NumberDecimalSeparator = ".";
height = Convert.ToDouble("3.14", c);
Judging by the result I take it you are in a culture zone where comma is the normal decimal separator.
Also, I take it that you want both dot and comma to be used for decimal separation.
If not, the below is not the proper solution.
The fastest solution for using both would be
height = Convert.ToDouble(heightString.Replace('.', ',');
This would mean that both dots and comma's are used as comma and thus parsed as a decimal separator.
If you only want to use a dot as separator, you can use invariantculture or a specific numberformatinfo. Invariant culture is already shown in the other posts. numberformat info example:
var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." };
height = double.Parse(heightString,nfi);
For completeness, the example below shows both using numberformatinfo for setting the dot as decimal separator, as well as replacing comma with dots, so both characters are used for decimals
var nfi = new NumberFormatInfo { NumberDecimalSeparator = "." };
height = double.Parse(heightString.Replace(',', '.'),nfi);
Different .Net cultures (countries) have different decimal separators.
If you expect input values to be in some specific format - either use some particular culture or InvariantCulture. Also consider using double.Parse as it geve more flexibility on parsing the values than generic Convert.ToDouble.
var d = double.Parse(heightString, CultureInfo.InvariantCulture);
If you expect user to enter value in local format - your code is fine, but either your expectation of "local format" is wrong, or "current culture" set incorrectly.
I am new to building web applications in ASP.NET and am trying to display a currency in Kenya Shillings. The symbol for the shilling is KES.
I have this:
<span>
<b>Price: </b><%#:String.Format(new System.Globalization.CultureInfo("sw-KE"), "{0:c}", Item.BeatPrice)%>
</span>
Culture name sourced from http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.80%29.aspx.
However, the price shows as S3,000 instead of KES 3,000.
What do I need to do to format the price correctly?
If the format is not as you expect you can add custom string formatting:
String.Format("KES {0:N3}", Item.BeatPrice)
Hope this works.
It's better not to hardcode the CurrencySymbol, so you should use
var regionInfo = new RegionInfo("sw-KE");
var currencySymbol = regionInfo.ISOCurrencySymbol;
to get the correct CurrencySymbol for your culture.
//edit:
Or you can try this function:
public static string FormatCurrency(decimal value)
{
CultureInfo cultureInfo = Thread.CurrentThread.CurrentUICulture;
RegionInfo regionInfo = new RegionInfo(cultureInfo.LCID);
string formattedCurrency = String.Format("{0} {1:C}", regionInfo.ISOCurrencySymbol, value);
return formattedCurrency.Replace(cultureInfo.NumberFormat.CurrencySymbol, String.Empty).Trim();
}
Which gives you a formatted currency string based on the current UICulture.
If your machine's regional settings are properly set then you can use:
Console.WriteLine(string.Format(CultureInfo.InvariantCulture, "{0:c}", Item.BeatPrice));
It will automatically take culture based on your machine's regional settings.
Like Ondrej Svejdar said, there are two symbols, as in $ vs. USD:
var region = new System.Globalization.RegionInfo("sw-KE");
Console.WriteLine(region.CurrencySymbol); // "S"
Console.WriteLine(region.ISOCurrencySymbol); // "KES"
Note: When I ran this on IDEone (which compiles with Mono), the results were unexpected ("KES" and "Kenyan Shilling").
While using String.Format "c" or "C" gives you the currency symbol for specified culture. You are trying to show Currency ISO code for Kenya Shillings. Below code will display exactly what you wanted.
String.Format("{0} {1}", (new RegionInfo("sw-KE")).ISOCurrencySymbol, Item.BeatPrice)
If you don't change culture on your application easy way to do this.
String.Format("{0} {1}", "KES", Item.BeatPrice)
The best practice is to format the String to Currency format {0:C} and change the current thread UICulture or Culture to KES, and ASP.NET is smart enough to display the page accroding to your currunt culuture.
Note:
You can change culture by changing the culture of the browser (you can to do this for development purposes) but best practice change the culture programmatically, for example here I'm change the culture base on user Cookie and mu default culture is en-us like this.
protected override void InitializeCulture()
{
HttpCookie cultureCookie = Request.Cookies["culture"];
if (cultureCookie == null)
{
cultureCookie = new HttpCookie("culture", "en-US");
Response.Cookies.Add(cultureCookie);
}
Thread.CurrentThread.CurrentCulture = new CultureInfo(cultureCookie.Value);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureCookie.Value);
base.InitializeCulture();
}
I feed a textbox a string value showing me a balance that need to be formatted like this:
###,###,###,##0.00
I could use the value.ToString("c"), but this would put the currency sign in front of it.
Any idea how I would manipulate the string before feeding the textbox to achieve the above formatting?
I tried this, without success:
String.Format("###,###,###,##0.00", currentBalance);
Many Thanks,
If the currency formatting gives you exactly what you want, clone a NumberFormatInfo with and set the CurrencySymbol property to "". You should check that it handles negative numbers in the way that you want as well, of course.
For example:
using System;
using System.Globalization;
class Test
{
static void Main()
{
NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat;
nfi = (NumberFormatInfo) nfi.Clone();
Console.WriteLine(string.Format(nfi, "{0:c}", 123.45m));
nfi.CurrencySymbol = "";
Console.WriteLine(string.Format(nfi, "{0:c}", 123.45m));
}
}
The other option is to use a custom numeric format string of course - it depends whether you really want to mirror exactly how a currency would look, just without the symbol, or control the exact positioning of digits.
string forDisplay = currentBalance.ToString("N2");
Have you tried:
currentBalance.ToString("#,##0.00");
This is the long-hand equivalent of:
currentBalance.ToString("N2");
string result=string.Format("{0:N2}", value); //For result like ### ### ##.##
You can do this with the group separator and the section separator, like this:
currentBalance.ToString("#,0.00;(#,0.00)");
This does not account for culture variances like the answer from #JonSkeet would, but this does mimic decimal place, rounding, thousands separation, and negative number handling that en-US culture currency format produces using a single custom format string.
.NET Fiddle Demo
var result = currentBalance.ToString("C").Replace(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol, "");
CultureInfo cultureInfo = new CultureInfo("en-US");
cultureInfo.NumberFormat.CurrencySymbol = "Rs.";
Thread.CurrentThread.CurrentCulture = cultureInfo;
decimal devimalValue = 3.45M;
this.Text = devimalValue.ToString("C2"); //Rs.3.45
This may be overkill, but it rounds, formats...
#helper TwoDecimalPlaces(decimal? val)
{
decimal x = 0;
decimal y = 0;
string clas = "text-danger";
if (val.HasValue)
{
x = (decimal)val;
if (val > 0)
{
clas = "";
}
}
y = System.Math.Round(x, 2);
IFormatProvider formatProvider = new System.Globalization.CultureInfo(string.Empty);
<span class="#clas">#string.Format("{0:N2}", y)</span>
}
This simple solution works for me with US currency.
If not needing international currency support use this and replace the $ with the currency symbol(s) to be removed:
// for USD
string result = currentBalance.ToString("C").Replace("$", "")
or
// for EUR
string result = currentBalance.ToString("C").Replace("€", "")