How can I do this formatting in a double - c#

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.

Related

How to do Number format in C#

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);

Strange output when converting string to double

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.

Convert a string number with comma to a culture specific double number

NumberFormatInfo numberInfo = CultureInfo.CurrentCulture.NumberFormat;
double result = Convert.ToDouble("2,75", numberInfo);
result = 2.75
My current UI/culture is "de-DE".
Why don't i get 2,75 ?
Because you are not getting a string result, but a double. How you then display that double later is not influenced by your code above.
If you want to see "2,75" on your screen, you need to format the double as a string, adding numberInfo.
Try this to get 2,75:-
string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:0.0}", 2.75);
or you can also try this:-
NumberFormatInfo n= new NumberFormatInfo();
n.NumberDecimalSeparator = ",";
n.NumberGroupSeparator = ".";
double d= 2.75;
string s= d.ToString(n); //2,75
You get 2.75. It's only different ways of displaying the number.
The double value contains no information about formatting. It's neither 2.75 nor 2,75, it's just a numeric value.
If you display the number using a culture that uses a comma as decimal separator, you will get what you expect, for example:
Console.WriteLine(result.ToString(CultureInfo.GetCultureInfo(1053)));
Output:
2,75

String.Format not converting integers correctly in arabic

I have a problem with String.Format. The following code formats the string correctly apart from the first integer. Current culture is set to Iraqi arabic (ar-IQ):
int currentItem= 1;
string of= "من";
int count = 2;
string formatted = string.Format(CultureInfo.CurrentCulture, "{0}{1}{2}", currentItem, of, count);
The text is formatted right to left and the 2 is converted to an arabic digit, but the 1 isn't.
Any ideas?
The default behaviour for converting numeric values is "Context", which basically means if a number is proceeded by Arabic they display in Arabic (or another "non-Latin" character), if they're not then they display in "standard" European numbers.
You can change that behaviour quite easily though:
var culture = CultureInfo.CurrentCulture;
culture.NumberFormat.DigitSubstitution = DigitShapes.NativeNational; // Always use native characters
string formatted = string.Format(culture, "{0:d}{1:d}{2:d}", currentItem, of, count);
That should work as you expect - more details on MSDN.
I couldn't get either of the other answers to work. This worked for me:
string sOriginal = "1 of 2";
var ci = new CultureInfo("ar-IQ", false);
var nfi = ci.NumberFormat;
string sNative = ReplaceWesternDigitsWithNativeDigits(sOriginal, nfi).Replace("of", "من");
...
private static string ReplaceWesternDigitsWithNativeDigits(string s, NumberFormatInfo nfi)
{
return s.Replace("0", nfi.NativeDigits[0])
.Replace("1", nfi.NativeDigits[1])
.Replace("2", nfi.NativeDigits[2])
.Replace("3", nfi.NativeDigits[3])
.Replace("4", nfi.NativeDigits[4])
.Replace("5", nfi.NativeDigits[5])
.Replace("6", nfi.NativeDigits[6])
.Replace("7", nfi.NativeDigits[7])
.Replace("8", nfi.NativeDigits[8])
.Replace("9", nfi.NativeDigits[9]);
}
var culture = CultureInfo.CurrentCulture;
culture.NumberFormat.DigitSubstitution = DigitShapes.NativeNational;
does not work,
but the following works:
var culture = new CultureInfo("ar-SA");
culture.NumberFormat = new NumberFormatInfo();
Thread.CurrentThread.CurrentCulture = culture;
Thanks for the hint!!!

Format a double value like currency but without the currency sign (C#)

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("€", "")

Categories