views:

2140

answers:

6

I wanting to show prices for my products in my online store. I'm currently doing:

<span class="ourprice">
     <%=GetPrice().ToString("C")%>
</span>

Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00"

I think the correct HTML for an output of "£12.00" is "&pound;12.00", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00.

(The server is in the UK, with localisation is set appropriately in web.config).

Is the below an improvement, or is there a better way?

<span class="ourprice">
     <%=GetPrice().ToString("C").Replace("£","&pound;")%>
</span>
+3  A: 

Try this, it'll use your locale set for the application:

<%=String.Format("{0:C}",GetPrice())%>
Nick Craver
AndyM
A: 

If you need to explicity state the localisation you can use the CultureInfo and pass that to the string formatter.

Slace
+2  A: 

Use

GetPrice().ToString("C", CultureInfo.CreateSpecificCulture("en-GB"))
Claus Thomsen
+1  A: 

You could write a function which would perform the conversion from price to string. This way you have a lot of control over the output.

The problem with locale is that it's web server dependent and not web browser dependent.

Peter Stuifzand
A: 

just use the ToString("C2") property of a decimal value. Set your globalization in the web.config - keep it simple.

typemismatch
+2  A: 

The £ symbol (U+00A3), and the html entities & #163; and & pound; should all render the same in a browser.

If the browser doesn't recognise £, it probably won't recognise the entity versions. It's in ISO 8859-1 (Latin-1), so I'd be surprised if a Mozilla browser can't render it (my FF certainly can).

If you see a $ sign, it's likely you have two things: 1. The browser default language is en-us 2. Asp.net is doing automatic locale switching. The default web.config setting is something like

<globalization   culture="auto:en-us"  uiCulture="auto:en-US" />

As you (almost certainly) want UK-only prices, simply specify the locale in web.config:

  <globalization   culture="us"  uiCulture="en-gb" />

(or on page level:)

  <%@Page Culture="en-gb" UICulture="en-gb" ..etc... %>

Thereafter the string formats such as String.Format("{0:C}",GetPrice()) and GetPrice().ToString("C") will use the en-GB locale as asp.net will have set the currentCulture for you

(although you can specify the en-gb culture in the overloads if you're paranoid).

martin