如何在 VB.NET 中格式化货币

1 vb.net

如何通过指定要使用的符号(例如 \xc2\xa3 或 $)来格式化 VB.NET 中的货币。

\n\n

我一直在使用 formatcurrency 但是我找不到更改值前面的符号的方法。

\n

Ňɏs*_*arp 5

使用像这样的遗留 VB 函数FormatCurrency是有限的,因为它们只知道当前的文化。 .ToString("C2")将使用当前区域性作为符号和小数点。要指定不同的文化:

\n\n
Dim decV As Decimal = 12.34D\n\nConsole.WriteLine("In France: {0}", decV.ToString("C2", New CultureInfo("fr-FR")))\nConsole.WriteLine("For the Queen! {0}", decV.ToString("C2", New CultureInfo("en-GB")))\nConsole.WriteLine("When in Rome: {0}", decV.ToString("C2", New CultureInfo("it-IT")))\nConsole.WriteLine("If you are Hungary: {0}", decV.ToString("C2", New CultureInfo("hu-HU")))\nConsole.WriteLine("For the US of A: {0}", decV.ToString("C2", New CultureInfo("en-US")))\n
Run Code Online (Sandbox Code Playgroud)\n\n

输出:

\n\n
\n

在法国:12,34 \xe2\x82\xac
\n 为了女王!\xc2\xa312.34
\n 在罗马时:\xe2\x82\xac 12,34
\n 如果您是匈牙利:12,34 英尺
\n 对于 A 的美国:$12.34

\n
\n\n

语言文化名称、代码表

\n\n
\n\n

您还可能在将外币字符串转换为值时遇到问题,因为CDec只知道如何使用本地文化。您可以使用Decimal.TryParse并指定传入的区域性:

\n\n
\' Croatian currency value\nDim strUnkVal = decV.ToString("C2", New CultureInfo("hr-HR"))\nDim myVal As Decimal\n\n\' if the string contains a valid value for the specified culture\n\' it will be in myVal\nIf Decimal.TryParse(strUnkVal,\n                    NumberStyles.Any,\n                    New CultureInfo("hr-HR"), myVal) Then\n    Console.WriteLine("The round trip: {0}", myVal.ToString("C2"))\nEnd If\n
Run Code Online (Sandbox Code Playgroud)\n