tags:

views:

3132

answers:

4

Is there a C# equivalent for the VB.NET FormatNumber function?

I.e.:

JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
+1  A: 

You can use string formatters to accomplish the same thing.

double MyNumber = inv.RRP * oCountry.ExchangeRate;
JSArrayString += "^" + MyNumber.ToString("#0.00");
d91-jal
+8  A: 

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.

John
For a full list of predefined number formatting options: http://msdn.microsoft.com/en-us/library/dwhawy9k.aspxAn alternative would be to use ToString("D2")
samjudson
+1  A: 

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

DonkeyMaster
A: 

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.

Jonathan Allen