简体   繁体   English

VB.NET FormatNumber在C#中等效?

[英]VB.NET FormatNumber equivalent in C#?

Is there a C# equivalent for the VB.NET FormatNumber function? 是否有VB.NET FormatNumber函数的C#等价物?

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. 在C#和VB.NET中,您可以使用.ToString()函数或String.Format()方法来格式化文本。

Using the .ToString() method your example could be written as: 使用.ToString()方法,您的示例可以写成:

JSArrayString += "^" + (inv.RRP * oCountry.ExchangeRate).ToString("#0.00")

Alternatively using the String.Format() it could written as: 或者使用String.Format(),它可以写成:

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. 在上述两种情况中,我都使用了货币的自定义格式,#表示可选的占位符,0表示0或值(如果存在)。

Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. 其他格式化字符可用于帮助格式化,例如D2为2位小数,或C为显示为货币。 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. 在这种情况下,您不希望使用C格式化程序,因为这将插入货币符号和不需要的其他分隔符。

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. 有关如何使用String.Format和不同格式选项的更多信息和示例,请参阅“ String.Format(”{0}“,”格式化字符串“}; ”或“ Int的字符串格式 ”。

Yes, the .ToString(string) methods. 是的,.ToString(字符串)方法。 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. 请注意,在C#中,您不使用数字来指定格式,而是使用字符或字符序列。 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. 在C#中格式化数字和日期需要花费几分钟的时间来学习,但是一旦理解了原理,您就可以通过查看参考快速获得所需的任何内容。

Here's a couple MSDN articles to get you started : 这里有几篇MSDN文章可以帮助您入门:

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#中的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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