How, for example, do I turn the number 10562.3093 into 10,562 in C#?
Also, how do I ensure that same formatter will apply correctly to all other numbers?....
...For example 2500.32 into 2,500
Help greatly appreciated.
string formatted = value.ToString("N0");
This divides your number in the manner specified by the current culture (in the case of "en-US," it's a comma per multiple of 1000) and includes no decimal places.
The best place to look for any question regarding formatting numbers in .NET would have to be here:
Standard Numeric Format Strings (MSDN)
And here:
Custom Numeric Format Strings (MSDN)
string.Format("{0:n0}", 10562.3093);
String.Format("{0:0,0}", 10562.3093);
I keep this website bookmarked for these purposes: String Formatting in C#
double x = 10562.3093;
x.ToString("#,0");
or
String.Format("{0:#,0}", 10562.3093);
Related
I am looking for a strategy to implement different currencies in my system.
For GB I use pounds locale and it works ok with numbers like "7.55", but as soon I change locale to Spanish for example I get the "7,55" number and I cannot handle it.
So the first thing is that I calculate some amount with JavaScript client side and JavaScript cannot calculate comma numbers, nor I can parseFloat, nor converting to decimal number if I don't replace commas with numbers like:
input.val().replace(',', '.');
I mean I don't understand how to handle this properly in scenarios when you have to make payment. When to convert for calculations, etc.
Is there any proper way to do this in .net with JavaScript help? Just need some tips.
In c#, you can use CultureInfo.InvariantCulture for this. You have a full snippet about currency here.
string str = "42.5";
float numFloat = float.Parse(str, CultureInfo.InvariantCulture);
Learn more from the msdn.
I am formatting the currency using Tostring() method i m using following syntax
ToString('##.##') it is working perfectly but in case of round number it remove last 2 zero
like for 100 it does not show 100.00 is shows 100.
how can i format in that way means
input desired output
100 100.00
100.10 100.10
Try "##.00" instead.
That will force two digits after the decimal separator.
You can also use ToString("C") to use the culture specific format in Windows directly.
First google result.
String.Format("{0:C}", x.ToString());
http://www.howtogeek.com/howto/programming/format-a-string-as-currency-in-c/
You can use :
.ToString("C")
Hope it helps.
Also, if you don't want the currency sign ($ in the US) added that "C" gives, you can also use "F2", which is "fixed number with 2 decimal places". It also has the advantage of giving you a thousands separator when you results go over 1,000.00.
This might help. Might be more than you need, but it takes globalization into account which might be necessary. "C" is also a short-cut currency format string that might get you further along.
I need to display float as
1.00
1.50
1.55
1.60
The following is what I see using f2 format.
1.
1.5
1.55
1.6
Is there a way to force the trailing 0 to appear?
(I'm using a DevExpress SpinEdit control and trying to set the display and edit format.)
yourNumber.ToString("N2");
You can use syntax like this:
String.Format("{0:0.00}", n)
For future reference,
http://www.csharp-examples.net/string-format-double/
On those rare occasions I need to formatting, I go here:
http://blog.stevex.net/index.php/string-formatting-in-csharp/
spinEdit.Properties.DisplayFormat.FormatType = FormatType.Numeric;
spinEdit.Properties.DisplayFormat.FormatString = "C2";
In the future, though, I would recommended searching Dev Express' knowledge base or emailing support (support#devexpress.com). They'll be able to answer your question in about a day.
You can also do this with string interpolation (note that this is C# 6 and above):
double num = 98765.4;
Console.WriteLine($"{num:0.00}"); //Replace "0.00" with "N2" if you want thousands separators
Let's say you had a variable called "myNumber" of type double:
double myNumber = 1520;
Instead of:
myNumber.ToString("N2"); // returns "1,520.00"
I would opt for:
myNumber.ToString("0.00"); // returns "1520.00"
since N2 will add "," thousands separators, which can often cause problems downstream.
How can I change values in string from 0,00 to 0.00? - only numeric values, not all chars "," to "."
FROM
string myInputString = "<?xml version=\"1.0\"?>\n<List xmlns:Table=\"urn:www.navision.com/Formats/Table\"><Row><HostelMST>12,0000</HostelMST><PublicMST>0,0000</PublicMST><TaxiMST>0,0000</TaxiMST><ParkMST>0,0000</ParkMST><RoadMST>0,0000</RoadMST><FoodMST>0,0000</FoodMST><ErrorCode>0</ErrorCode><ErrorDescription></ErrorDescription></Row></List>\n";
TO
string myInputString = "<?xml version=\"1.0\"?>\n<List xmlns:Table=\"urn:www.navision.com/Formats/Table\"><Row><HostelMST>12.0000</HostelMST><PublicMST>0.0000</PublicMST><TaxiMST>0.0000</TaxiMST><ParkMST>0.0000</ParkMST><RoadMST>0.0000</RoadMST><FoodMST>0.0000</FoodMST><ErrorCode>0</ErrorCode><ErrorDescription></ErrorDescription></Row></List>\n";
Thanks for answers, but I mean to change only numeric values, not all chars "," to "."
I don't want change string from
string = "<Attrib>txt txt, txt</Attrib><Attrib1>12,1223</Attrib1>";
to
string = "<Attrib>txt txt. txt</Attrib><Attrib1>12.1223</Attrib1>";
but this one is ok
string = "<Attrib>txt txt, txt</Attrib><Attrib1>12.1223</Attrib1>";
Try this :
Regex.Replace("attrib1='12,34' attrib2='43,22'", "(\\d),(\\d)", "$1.$2")
output : attrib1='12.34' attrib2='43.22'
The best method depends on the context. Are you parsing the XML? Are you writing the XML. Either way it's all to do with culture.
If you are writing it then I am assuming your culture is set to something which uses commas as decimal seperators and you're not aware of that fact. Firstly go change your culture in Windows settings to something which better fits your culture and the way you do things. Secondly, if you were writing the numbers out for human display then I would leave it as culturally sensative so it will fit whoever is reading it. If it is to be parsed by another machine then you can use the Invariant Culture like so:
12.1223.ToString(CultureInfo.InvariantCulture);
If you are reading (which I assume is what you are doing) then you can use the culture info again. If it was from a human source (e.g. they typed it in a box) then again use their default culture info (default in float.Parse). If it is from a computer then use InvariantCulture again:
float f = float.Parse("12.1223", CultureInfo.InvariantCulture);
Of course, this assumes that the text was written with an invariant culutre. But as you're asking the question it's not (unless you have control over it being written, in which case use InvariantCulture to write it was suggested above). You can then use a specific culture which does understand commas to parse it:
NumberFormatInfo commaNumberFormatInfo = new NumberFormatInfo();
commaNumberFormatInfo.NumberDecimalSeperator = ",";
float f = float.Parse("12,1223", commaNumberFormatInfo);
I strongly recommend joel.neely's regex approach or the one below:
Use XmlReader to read all nodes
Use double.TryParse with the formatter = a NumberFormatInfo that uses a comma as decimal separator, to identify numbers
Use XmlWriter to write a new XML
Use CultureInfo.InvariantCulture to write the numbers on that XML
The answer from ScarletGarden is a start, but you'll need to know the complete context and grammar of "numeric values" in your data.
The problem with the short answer is that cases such as this get modified:
<elem1>quantity<elem2>12,6 of which were broken</elem2></elem1>
Yes, there's probably a typo (missing space after the comma) but human-entered data often has such errors.
If you include more context, you're likely to reduce the false positives. A pattern like
([\s>]-?$?\d+),(\d+[\s<])
(which you can escape to taste for your programming language of choice) would only match when the "digits-comma-digits" portion (with optional sign and currency symbol) was bounded by space or an end of an element. If all of your numeric values are isolated within XML elements, then you'll have an easier time.
string newStr = myInputString.Replace("0,00", "0.00");
While you could theoretically do this using a Regex, the pattern would be complex and hard to to test. ICR is on the right track, you need to do this based on culture.
Do you know that your numbers are always going to be using a comma as a decimal separator instead of a period? It looks like you can, given that Navision is a Danish company.
If so, you'll need to traverse the XML document in the string, and rewrite the numeric values. It appears you can determine this on node name, so this won't be an issue.
When you convert the number, use something similar to this:
here's what you want to do:
internal double ConvertNavisionNumber(string rawValue)
{
double result = 0;
if (double.TryParse(rawValue, NumberStyles.Number, new CultureInfo("da-DK").NumberFormat, out result))
return result;
else
return 0;
}
This tells the TryParse() method that you're converting a number from Danish (da-DK). Once you call the function, you can use ToString() to write the number out in your local format (which I'm assuming is US or Canadian) to get a period for your decimal separator. This will also take into account numbers with different thousands digit separator (1,234.56 in Canada is written as 1 234,56 in Denmark).
ConvertNavisionNumber("4,43").ToString()
will result in "4.43".
ConvertNavisionNumber("1 234").ToString()
will result in "1,234".
if the , is not used anywhere else but number with in the string you can use the following:
string newStr = myInputString.Replace(",", ".");
Is there a C# equivalent for the VB.NET FormatNumber function?
I.e.:
JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
In both C# and VB.NET you can use either the .ToString() function or the String.Format() method to format the text.
Using the .ToString() method your example could be written as:
JSArrayString += "^" + (inv.RRP * oCountry.ExchangeRate).ToString("#0.00")
Alternatively using the String.Format() it could written as:
JSArrayString = String.Format("{0}^{1:#0.00}",JSArrayString,(inv.RRP * oCountry.ExchangeRate))
In both of the above cases I have used custom formatting for the currency with # representing an optional place holder and 0 representing a 0 or value if one exists.
Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. In this case you would not want to use the C formatter as this would have inserted the currency symbol and further separators which were not required.
See "String.Format("{0}", "formatting string"};" or "String Format for Int" for more information and examples on how to use String.Format and the different formatting options.
Yes, the .ToString(string) methods.
For instance,
int number = 32;
string formatted = number.ToString("D4");
Console.WriteLine(formatted);
// Shows 0032
Note that in C# you don't use a number to specify a format, but you use a character or a sequence of characters.
Formatting numbers and dates in C# takes some minutes to learn, but once you understand the principle, you can quickly get anything you want from looking at the reference.
Here's a couple MSDN articles to get you started :
Standard Numeric Format Strings
Formatting Types
You can use string formatters to accomplish the same thing.
double MyNumber = inv.RRP * oCountry.ExchangeRate;
JSArrayString += "^" + MyNumber.ToString("#0.00");
While I would recommend using ToString in this case, always keep in mind you can use ANY VB.Net function or class from C# just by referencing Microsoft.VisalBasic.dll.