简体   繁体   English

C#中的CultureInfo

[英]CultureInfo in C#

My system is id-ID, using ',' as decimal separator. 我的系统是id-ID,使用','作为十进制分隔符。 I have problems with data in en-US, I want to convert it to id-ID and then back to en-US : 我在en-US中遇到数据问题,我想将其转换为id-ID,然后再返回到en-US:

 List<string> list = new List<string>(){"0.14","223.54"}; // en-US

 list[0] = Convert.ToDecimal(list[0], CultureInfo.InvariantCulture).ToString();
 MessageBox.Show("list[0] = " + list[0]); //display "0,14", it is ok!
 MessageBox.Show("list[1] = " + list[1]); //display "223,54", it is ok!

Now I want to change it back to US culture, I can simply use Replace to change ',' back to '.' 现在,我想将其更改回美国文化,只需使用“替换”将“,”更改回“。” as US culture. 作为美国文化。

 MessageBox.Show("list[0] = " + list[0].Replace(",", ".")); //displays  "0.14"

But it is not an elegant way to handle it, I wish I can handle it with CultureInfo, so I try the following statements but can't work! 但这不是一种优雅的处理方式,我希望可以使用CultureInfo处理它,因此我尝试了以下语句,但无法正常工作!

 CultureInfo us = new CultureInfo("en-US");
 list[0] = Convert.ToDecimal(list[0], us).ToString();
 list[1] = Convert.ToDecimal(list[1], us).ToString();
 MessageBox.Show("list[0] = " + list[0]); //display "14", the decimal separator is missing!
 MessageBox.Show("list[1] = " + list[1]); //display "223,54", nothing changed!

en-US culture uses comma as a number group separator. 美国文化使用逗号作为数字组分隔符。 This a reason of the mistake. 这是错误的原因。 Better approach is to store decimal as decimal. 更好的方法是将十进制存储为十进制。 Use required culture when you output data: 输出数据时,请使用必需的区域性:

List<string> stringList = new List<string>() { "0.14", "223.54" };
List<decimal> list = stringList.Select(Convert.ToDecimal).ToList();

MessageBox.Show(list[0].ToString(CultureInfo.InvariantCulture));
MessageBox.Show(list[0].ToString(new CultureInfo("en-US")));
MessageBox.Show(list[0].ToString(new CultureInfo("id-ID")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM