Money Format Number VB.NET
-
29-04-2021 - |
Question
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.
Solution
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
OTHER TIPS
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)
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
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"))
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..)
Dim num1 As Decimal = 20
Dim num2 As Decimal = 34
Dim ans As Decimal
ans = num1 + num2
MsgBox(ans.ToString("c"))
Take a look at the String.Format documentation, you will find what you need there.
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.