问题
I'm trying to convert a mathematical result of money format example:
Dim num1 As Integer = 2000
Dim num2 As Integer = 500
msgbox(cDbl(num1 + num2))
It only returns 2500, which I need to return my 2,500.00 if anyone has any idea how I would be very helpful thanks.
回答1:
Your MsgBox
shows you the value, but it hasn't formatted it, as you haven't asked it to.
If you went a little further and formatted the result as a string, you'll get the format you desire, e.g:
Dim num1 As Double = 2000
Dim num2 As Double = 500
Dim sum As Double = num1 + num2
MsgBox(sum.ToString("0.00")) ' Adjust format string to suit
回答2:
First, you should use Decimal
instead of Double
when handling monetary values. Double
has some rounding issues.
Second, you can use string formatting:
Dim num1 As Integer = 2000
Dim num2 As Integer = 500
Diml value As Decimal = CDec(num1 + num2)
Dim formattedValue As String = String.Format("{0:n}", value)
msgbox(formattedValue)
回答3:
Standard Numeric Format String
is a great resource for general number formatting, the top one being currency (this takes into account culture differences)
"C" or "c" for Currency
- Supported by: All numeric types.
- Precision specifier: Number of decimal digits.
- Default precision specifier: Defined by System.Globalization.NumberFormatInfo.
More information: The Currency ("C") Format Specifier.
- 123.456 ("C", en-US) -> $123.46
- 123.456 ("C", fr-FR) -> 123,46 €
- 123.456 ("C", ja-JP) -> ¥123
- -123.456 ("C3", en-US) -> ($123.456)
- -123.456 ("C3", fr-FR) -> -123,456 €
- -123.456 ("C3", ja-JP) -> -¥123.456
回答4:
If you want the format to be currency, either of these will work:
Dim num1 As Integer = 2000
Dim num2 As Integer = 500
MsgBox(String.Format("{0:C2}", num1 + num2))
Or
Dim num1 As Integer = 2000
Dim num2 As Integer = 500
Dim sum As Integer = num1 + num2
MsgBox(sum.ToString("C2"))
回答5:
formatcurrency to double
value = 1500,20 TL
ctype(value, double)
return 1500,20
double to formatcurrency
sample
value = 1500,1995
formatcurrency(value,2)
return = 1500,20 TL moneysembol (TL , $ ,vs..)
回答6:
Take a look at the String.Format documentation, you will find what you need there.
回答7:
You normally don't use Integer
as the Datatype for currency values. Use Double
instead.
I'm sure there are many ways to format the output string as a currency value.
One if the methods I know has already been explained by Rowland Shaw. So I'll skip to the other one. It is the built-in function called FormatCurrency
. It will output the string as a currency value plus with the currency symbol defined in your system.
Dim num1 As Double = 2000
Dim num2 As Double = 500
Dim ans As Double = num1 + num2
MessageBox.Show(FormatCurrency(ans))
More details on FormatCurrency
, look here.
来源:https://stackoverflow.com/questions/9265389/money-format-number-vb-net