开发者

how to convert english decimal to spanish decimal, using globalization in c#

开发者 https://www.devze.com 2023-02-08 18:35 出处:网络
im using visual studio 2008. my desktop application runs in different regional settings. in my code, i have decimal numbers in string variables in english format, i want to convert them to decimal va

im using visual studio 2008. my desktop application runs in different regional settings.

in my code, i have decimal numbers in string variables in english format, i want to convert them to decimal variables using Convert.ToDecimal() with regional settings as "Spanish (Ecuador).

when i do the following:

string myNum = "0.04";  
decimal myDec = Convert.ToDecimal(开发者_如何学PythonmyNum); // here im getting 4 instead of 0,04

when i used,

Convert.ToDecimal(myNum, new CultureInfo("en-US")); // i got 0.04, but i want 0,04

i cant add the new CultureInfo("en-Us") for every statement, coz i have used conversion statements more than 100 times.

how do i achieve this. please help??


Rather than creating a new culture each time, it would be better to use CultureInfo.InvariantCulture - and I would personally use decimal.Parse or decimal.TryParse rather than Convert.ToDecimal. Just my personal preference though. IIRC they only really differ in terms of handling null input.

However, if you're just objecting to including that in your code each time, the simplest solution would be to write your own helper method and call that. For example:

public static decimal ParseDecimalInvariant(string text)
{
    return decimal.Parse(text, CultureInfo.InvariantCulture);
}

As an aside, I hope you don't really have the string values in your code. If you've got strings which represent numbers, just change them to literals instead!

decimal myNum = 0.04m;

That's much better than parsing at execution time :)


I believe the correct answer here is going to involve code changes. You can change the app's culture, but IMO that is incorrect since it overrides the user's preferences for display etc.

Normally, you would throw the required culture the code uses into a static field somewhere, and pass that culture in for every bit of your code that interprets a system string literal. In your cases, since the code literals are in an english format, you can pass in CultureInfo.InvariantCulture each time and save some effort.

Yes, it'll be 100 code changes; frankly: tough.

0

精彩评论

暂无评论...
验证码 换一张
取 消