vb.net 将字符串转换为货币格式而不先转换为数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9906263/
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-09 16:01:21  来源:igfitidea点击:

Convert string to currency format without casting to numerical value first

vb.net

提问by ipr101

This code -

这段代码——

Convert.ToDecimal("28.9100000000000000").ToString("c")

will convert a string containing a decimal value to a nicely formatted currency value. Is there anyway to do this without first converting the string value to a decimal?

将包含十进制值的字符串转换为格式良好的货币值。无论如何,如果不先将字符串值转换为十进制,就可以这样做吗?

采纳答案by Oded

In order to preserve culture specific currency attributes (currency symbol, separators and precision), your current approach looks like the best one.

为了保留特定于文化的货币属性(货币符号、分隔符和精度),您当前的方法看起来是最好的方法。

If you know the precision and don't care about cultures, you can do some simple string manipulation:

如果你知道精度并且不关心文化,你可以做一些简单的字符串操作:

 "$" & myString.Substring(0, myString.IndexOf(".") + 3)

回答by Gatesay

A simple method that I use:

我使用的一个简单方法:

MoneyString = string.format("{0:C}",DecimalValue)

回答by Andrew Cooper

How about this?

这个怎么样?

decimalString = "28.910000000000000000"
currencyString = "$" + decimalString.SubString(0, decimalString.IndexOf('.') + 3)

Of course, if you're going to do this you also need to worry about locale settings. Probably just as easy to do the numeric conversion, and let the framework do the formatting for you.

当然,如果您打算这样做,您还需要担心区域设置。进行数字转换可能同样容易,让框架为您进行格式化。