MunkiPhD
MunkiPhD

Reputation: 3644

.Net Converting a number from one culture to another

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)?

Upvotes: 4

Views: 3180

Answers (3)

dove
dove

Reputation: 20674

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.

Upvotes: 3

Rockcoder
Rockcoder

Reputation: 8479

You can use NumberFormatInfo class to do that.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500355

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.

Upvotes: 7

Related Questions