vb.net 更改货币格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16782894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:45:48  来源:igfitidea点击:

Change Currency Format

asp.netvb.netstringcurrency

提问by Sabilv

I Have a field that should consist a currency, which is according to my Region is Indonesia which is IDR or Rp. and i build it with string.formatlike this :

我有一个应该包含货币的字段,根据我的地区是印度尼西亚,它是 IDR 或 Rp。我用string.format这样的方式构建它:

 Dim price As Single = Single.Parse(Convert.ToSingle(lblAmountGV.Text))
 lblAmount.Text = String.Format("{0,C}", price)

but it give me a dollar sign. and i Change the code :

但它给了我一个美元符号。我更改代码:

 lblAmount.Text = String.Format("Rp{0}", price)

but i didn't get the dot (.)and Comma(,). so I change the code again by using FormatCurrency:

但我没有得到dot (.)and Comma(,)。所以我再次使用FormatCurrency以下代码更改代码:

 lblAmount.Text = FormatCurrency(lblAmountGV.Text, , , TriState.True, TriState.True)

but it still give me a Dollar sign, later i found how to change the CultureInfo:

但它仍然给我一个美元符号,后来我找到了如何改变CultureInfo

by imports :

按进口:

Imports System.Globalization

and on my code :

在我的代码上:

 Dim culture = CultureInfo.GetCultureInfo(" id-ID")
    Dim format = DirectCast(culture.NumberFormat.Clone(), NumberFormatInfo)
    format.CurrencySymbol = "Rp."
    var number = Decimal.Parse(lblAmountGV.Text, NumberStyles.Currency, format);

lblAmount.Text = number

but it still give me an $sign, how to change the $programatically?

但它仍然给我一个$标志,如何以$编程方式更改?

回答by pstrjds

I see a couple issues with what you posted -

我发现您发布的内容存在一些问题-

this line is incorrect

这条线不正确

String.Format("{0,C}", price)

You need to use a colon to add additional formatting arguments. If you want to format currency with decimal places than you also need to indicate the number of decimal digits. It should be something like this

您需要使用冒号来添加其他格式参数。如果要使用小数位格式化货币,则还需要指明小数位数。它应该是这样的

String.Format("{0:C2}", price)

And this line has an extra space that causes it to fail with a CultureNotFoundException

这条线有一个额外的空间,导致它失败 CultureNotFoundException

CultureInfo.GetCultureInfo(" id-ID")

Should be

应该

CultureInfo.GetCultureInfo("id-ID")

This code worked for me:

这段代码对我有用:

Dim culture As CultureInfo = CultureInfo.GetCultureInfo("id-ID")
Dim price As Double = 10.05

Dim result As String = String.Format(culture, "{0:C2}", price)

You can see it in action here

你可以在这里看到它的实际效果

If you are familiar with LINQPad, you can paste the following into LINQPad and see the proper formatting without the dollar sign -

如果您熟悉LINQPad,可以将以下内容粘贴到 LINQPad 中,并查看不带美元符号的正确格式 -

String.Format(CultureInfo.GetCultureInfo("id-ID"), "{0:C2}", 10.05).Dump()