I have this value : 12345678,99
I'd like have this : €12.345.678 to resume "." as thousand separator, not show decimal number and add the € befor the number.
Do you know the formatting string ?
Thanks,
This MSDN tutorial might be of help. This list provides a list of cultures you can use. Since you want to use the . as a thousand seperator and use the Euro currency, you should be fine using the Italian locale, it-IT.
Lots of examples:
http://www.csharp-examples.net/string-format-double/
http://blog.stevex.net/string-formatting-in-csharp/
You can build your own formatter if the style you want isn't specific to a culture (note the console shows a ? for the € symbol on the default font, that doesn't mean it hasn't worked):
private static void Main(string[] args)
{
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencySymbol = "€";
nfi.CurrencyGroupSeparator = ".";
nfi.CurrencyDecimalSeparator = ".";
decimal val = 300099.99M;
Console.WriteLine(val.ToString("c", nfi));
Console.Read();
}
If it is specific to a culture, then you can do the following (adapted from MSDN with npinti's suggested culture of it-IT):
public static void Main()
{
int i = 100;
CultureInfo it = new CultureInfo("it-IT");
Console.WriteLine(i.ToString("c", it));
Console.Read();
}
Try this:
double jjj = 12345678.99d;
NumberFormatInfo nfi = new CultureInfo("en-GB", false).NumberFormat;
nfi.CurrencyGroupSeparator = ".";
MessageBox.Show(jjj.ToString("C0", nfi));
You need to use a culture with the right seperator and a bit of custom formatting to round the decimal values and prepend the currency symbol.
somthing like,
var value = 12345678.99m;
return value.ToString("€00,##0", CultureInfo.CreateSpecificCulture("el-GR"));
If your culture have the right currency symbol I think this is better,
return value.ToString("C0", CultureInfo.CreateSpecificCulture("el-GR"));
Related
I'm a doubt when formatting a number of type double.
I would like it to be from 250000.0 to 250.000
With dot and not comma
Another example: from 26000 to 26.000
You can use The Numeric ("N") Format Specifier.
To force specific thousands separator, specify NumberGroupSeparator.
var num = 250000.0;
NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;
nfi.NumberGroupSeparator = ".";
var numString = num.ToString("N0", nfi);
Try this:
var value = 250000.0;
var text = value.ToString("N0", CultureInfo.GetCultureInfo("de-DE"));
This gives 250.000 as you asked.
You can simply replace the culture code, "de-DE", with one that gives you the output you need.
There are lot of format specifier in .net e.g. C for currency, D for decimal.
Lot of defined formats can be here.
How can I get exact format behind format specifier as per given locale.
E.g. (I assume here en-US locale)
GetFormatSpecifierText("C") should return me "$" #,##0.00
GetFormatSpecifierText("F") should return me "#,##0.00
Look at how Culture is used in combination with the format specifiers. I believe you may be looking for the override in the below code from MSDN:
public class userOverrideSample
{
[WebMethod]
public String UserLocalSetting()
{
int i = 100;
// Sets the CurrentCulture to French in France.
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
// Displays i formatted as currency for the CurrentCulture.
// Due to operating system differences, you cannot be sure what currency
// symbol will be used.
return (i.ToString("c"));
}
[WebMethod]
public String OverrideUserSetting()
{
int i = 100;
// Sets the CurrentCulture to French in France.
// Uses the CultureInfo constructor that takes a
// useUserOverride parameter.
// Sets the useUserOverride value to false.
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR", _
false);
// Displays i formatted as currency for the CurrentCulture.
// This will override any user settings and display the euro symbol.
return (i.ToString("c"));
}
}
I write below code to get currency format pattern.
Here, passed param numberFormat as [Currency]#,##0.00 and fr-FR locale; and got # ##0,00 "€" as desire and expected o/p.
static string[] CurrencyPositivePattern = { "$n", "n$", "$ n", "n $" };
static string[] CurrencyNegativePattern = { "($n)", "-$n", "$-n", "$n-", "(n$)",
"-n$", "n-$", "n$-", "-n $", "-$ n",
"n $-", "$ n-", "$ -n", "n- $", "($ n)",
"(n $)" };
internal static string GetCurrencyPattern(System.Globalization.NumberFormatInfo numberFormatInfo, string numberFormat)
{
numberFormat = numberFormat.Replace("[Currency]", string.Empty);
int pos = numberFormatInfo.CurrencyPositivePattern;
int neg = numberFormatInfo.CurrencyNegativePattern;
string currencySymbol = string.Format("\"{0}\"", numberFormatInfo.CurrencySymbol);
string excelPattern = string.Concat(CurrencyPositivePattern[pos].Replace("n", numberFormat).Replace("$", currencySymbol),
";",
CurrencyNegativePattern[neg].Replace("n", numberFormat).Replace("$", currencySymbol));
return excelPattern;
}
Few References that I used for implementation:
https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencypositivepattern(v=vs.110).aspx
As I stucked at specific Currency format for excel, I write Currency specific code. Others formats are easily handled by excel (same also commented by Murray Foxcroft in answer's comment).
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 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
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("€", "")