ToString() method culture-based in web application
For instance:
double d = 2.24;
If Culture is 'fr'
d.ToString() -> "2,24"
If culture is 'en'
d.ToString() -> "2.24"
This implicit culture-based cast can generate lot of mistakes.
In aspx.cs
<script>
var n = <% Response.Write(d.ToString())开发者_StackOverflow; %> // if 'fr' n = 2,24 -> js syntax error
</script>
We can avoid that with
Convert.ToString(d, CultureInfo.InvariantCulture);
Is there any option to made this InvariantCulture
by default for ToString()?
Any idea why it is done by Default?
You could use the <globalization>
element of your web.config and set a culture and a UI culture. For example:
<system.web>
<globalization culture="en-US" uiCulture="en-US">
</system.web>
By the way instead of:
<script>
var n = <% Response.Write(d.ToString()); %> // if 'fr' n = 2,24 -> js syntax error
</script>
I would recommend you to always use JavaScriptSerializer in order to JSON serialize the value when passing data to javascript:
<script>
var n = <%= new JavaScriptSerializer.Serialize(d) %>;
</script>
精彩评论