Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 269
MunkiPhD Avatar asked Dec 31 '22 08:12

MunkiPhD


2 Answers

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.

like image 125
Jon Skeet Avatar answered Jan 14 '23 15:01

Jon Skeet


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.

like image 21
dove Avatar answered Jan 14 '23 17:01

dove