views:

577

answers:

3

Quick question --

In .Net (VB more specifically, but that doesn't really matter), is there a way to change the format of a number from one culture to another strictly through the that number's type?

The issue is this: In English, the number is say, 123.45. Whereas in Sweden, the number would be 123,45

Is there a way to convert 123,45 to 123.45 without having to convert it to a string (and then use the formatting methods) then convert it back to the correct type (single, double, etc)?

Thanks

+3  A: 

Leave it as a number. Change the cultureInfo of the thread and it will display accordingly with no need of conversion.

E.g.

Thread.CurrentThread.CurrentCulture = New CultureInfo("se-SE")
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture

Never try and specifically format numbers or dates into strings or you will be on your way to hell.

UPDATE: Jon makes a point to be aware of in comments, you'll know if it applies to your situation or not.

dove
Changing the CultureInfo of the thread sounds like a riskier way of doing it than explicitly formatting with a particular CultureInfo when you want to format it. Of course, if it makes sense for the whole thread to change culture, that's fine - but I wouldn't change culture, format, then change back
Jon Skeet
you've got point, i'm assuming the entire view will be in swedish. Of course if he wants to display both on the same page according to two cultures, then format control according to relevant cultureInfo for that control.
dove
The issue was not the DISPLAY of it, it's that the application was saving the values incorrectly into the database, so .07 was written as ,07 and when the value was read/updated, the DB converted it into 7 (english). I've been trying to create a disconnect between the presentation and the data lyr.
MunkiPhD
+5  A: 

It wouldn't be a case of converting into a string and then back to the correct type - quite the opposite.

The number itself doesn't have any formatting information about it. A float is a float is a float. It's only when you parse or format that the culture becomes relevant.

If you've already got a float value, then just format it appropriately based on the culture of whoever's reading it.

Jon Skeet
A: 

You can use NumberFormatInfo class to do that.

Mr. Brownstone