Question Format price

icycold68

Active member
Joined
Oct 16, 2012
Messages
30
Programming Experience
3-5
Hello,

I am trying to format prices to two decimal places, but seem unable to find a way to do this. The code I am using at present is as follows (were product_price is the name of the variable containing the price):

lblPrice.Text = String.Format("{0:#.0}", product_price)

This, however, like other methods I have used does not format the prices correctly.

The prices are currently displayed in the following formats:

3999
999
467000

What I need is for them to be displayed in a correct currency format e.g., 3999 should be displayed as £39,99.

Is there an easy way to do this please?

Thanks!
 
Thanks for your help Ian, however, when I try this I get the following error:

Name 'FormatCurreny' is not declared.

This is how I have referenced it in my code:

formatted_product_price = FormatCurreny(product_price)
 
Thank you Ian, that works to an extent, however, it is still not formatting the price to 2 decimal places. For example, the price 1999 should be displayed as £19.99, whereas at present it is displayed as £1,999.00.

Any ideas why please?
 
Hi,

The FormatCurrency function is looking for a decimal value when it does it's conversion to currency so when you send "1999" as a parameter to the function it will assume that an integer value of 1999 has a decimal value of zero and therefore append a .00 the end of it resulting in £1,999.00.

If you know that your price strings will always be in a format where pounds and pence are NOT separated by a period then you need to deal with this yourself before calling the FormatCurrency function. i.e:-

VB.NET:
Dim cur As String = "1999"
MsgBox(FormatCurrency(Decimal.Parse(cur.Substring(cur.Length - 2) & "." & cur.Substring(cur.Length - 2, 2))))
Hope this helps,

Cheers,

Ian
 
There's a much shorter way to format numbers as currency:

Dim cur as Double = 1999
Dim str As String = cur.ToString("c")
MessageBox.Show(str)
 
You should be simply dividing by 100 if what you have is a number of pence. I have to agree with Solitaire that you should be using ToString rather than FormatCurrency too. I tend to avoid VB6 hold-overs like that unless they offer some genuine value, which FormatCurrency does not. Use String.Format for composite formats and ToString for simple ones.
 
Back
Top