I have a .NET app that allows a user to choose their own language & culture (date/number formatting). Their culture setting is stored in Thread.CurrentThread.CurrentCulture (also Thread.CurrentThread.CurrentUICulture, but that’s a separate issue).
When I print out a var via Razor, it shows in localized format:
<span>@bignum</span> (renders as "123.456" or "123,456")
However, I also need to pass some .NET vars to Javascript:
var js_bignum = @bignum;
The problem is that Javascript in this case does not understand the localized versions of these numbers, so it fails since the above statement becomes:
var js_bignum = 123,456;
It may be because the user’s browser’s culture setting is different from the user’s webapp’s culture setting. At any rate, it’s a situation we need to be able to handle.
So what’s the easiest way to handle this? I can create my own Javascript ConvertToStandardNumberFormat() that takes a string value from .NET and returns a “standard” number format, but that seems like a bit of a hack. Is there a way to force .NET/razor to render a non-localized format number?
var js_bignum = @price.ToUnlocalizedFormat(); (Is there something like this?)
I’m just trying to figure out what the best practices are for this type of situation.
Thanks!
I would use
@price.ToString(CultureInfo.InvariantCulture)Edit
I have to disagree with João answer and would consider it a Bad Idea™. I would not recommend re-inventing the wheel. If you would prefer a more comprehensive approach, then I would opt to include a dedicated C# JSON encoding library (I would recommend JsonFx.NET).
The most simple approach, I would make an HtmlHelper extension. Something like:
Then use it in a view with:
This should handle primitive types as well as complex types.
After that I would probably refactor things and try to come up with a better injection pattern so that I’m not creating a new
JsonWriterwith each call to the helper.But this will be much more flexible (and tested) than rolling your own serializer in the form of a static helper class…