简体   繁体   中英

VB.NET FormatNumber equivalent in C#?

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

Ie:

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

虽然我建议在这种情况下使用ToString,但请记住,只需引用Microsoft.VisalBasic.dll即可使用任何VB.Net函数或C#中的类。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM