我正在读取包含值的XML文件。当我读它们时,它们就是字符串。
因此,当我尝试将它们转换为Double
或Decimal
时,该点就会消失。
decimal dec = Convert.ToDecimal("3.1922");
MessageBox.Show(dec.ToString()); // 31922
我做错了什么?
答案 0 :(得分:4)
它与您当前的文化有关
decimal dec = Convert.ToDecimal("3.1922",CultureInfo.CreateSpecificCulture("de-DE"));
MessageBox.Show(dec.ToString()); //31922
dec = Convert.ToDecimal("3.1922", CultureInfo.CreateSpecificCulture("en-US"));
MessageBox.Show(dec.ToString()); //3.1922
dec = Convert.ToDecimal("3,1922", CultureInfo.CreateSpecificCulture("de-DE"));
MessageBox.Show(dec.ToString()); //3.1922
答案 1 :(得分:1)
在您当前的文化中,.
用作千位分隔符。您可以这样验证:
var culture = Thread.CurrentThread.CurrentCulture;
var numberFormat = culture.NumberFormat;
string groupSeparator = numberFormat.NumberGroupSeparator; // will be .
string decimalSeparator = numberFormat.NumberDecimalSeparator; // will be ,
您可以指定所需的解析文化:
decimal dec = Decimal.Parse("3.1922", new CultureInfo("en-US"));
或者您可以将您的文化设置为最新:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
decimal dec = Decimal.Parse("3.1922");
答案 2 :(得分:0)
检查您的NumberFormat.NumberDecimalSeparator。
答案 3 :(得分:-2)
首先在public form1()
after InitializeComponent();
中添加这些代码:
public Form1()
{
InitializeComponent();
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
然后在任何地方使用您的代码:
decimal dec = Convert.ToDecimal("3.1922");
MessageBox.Show(dec.ToString());
更新:
如果您不想进行全局更改,则应在显示小数之前添加代码。
private void ShowDecimal_Click(object sender, EventArgs e)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
decimal dec = Convert.ToDecimal("3.1922");
MessageBox.Show(dec.ToString());
}
更新2:
decimal dec = Decimal.Parse("3.1922", new CultureInfo("en-US"));
MessageBox.Show(dec.ToString());