I'm making a quick program in C# and I have a problem with character used as decimal point. Right now, I need to use
,
but I want to be able to use
.
or even better, both.
I'm looking for some short and easy solution, because the whole program is a hack, and I doubt that, except for this one point, I'll ever need to make it look better.
Here's one of the problematic pieces of code:
private void button2_Click(object sender, EventArgs e)
{
double Ri, B, R, T;
Ri = Convert.ToDouble(textBox2.Text);
B = Convert.ToDouble(textBox3.Text);
R = Convert.ToDouble(textBox6.Text);
T = B / Math.Log(R*1000 / Ri, Math.Exp(1)) - 273.15;
textBox5.Text = T.ToString();
}
I'm using automatically generated button and I just plaed the formula I need to have cal开发者_运维问答culated into it. As you can see, right now I'm using Convert.ToDouble, for conversion. Are there any better ways to do it? I'd also like, if possible, to avoid going through the string and looking for dots and commas and fixing them by hand.
I also have a feeling that the problem is related to locale setting on my system, but I'd rather not change it at this time.
For the comma, change your last line to:
textBox5.Text = T.ToString(CultureInfo.GetCultureInfo("de-DE").NumberFormat);
For the period, use this:
textBox5.Text = T.ToString(CultureInfo.InvariantCulture.NumberFormat);
// or use any "normal" country
And to do the reverse (parse the original value in the text box), do this for the comma:
double d = double.Parse(textBox5.Text, CultureInfo.GetCultureInfo("de-DE").NumberFormat);
And this for the period:
double d = double.Parse(textBox5.Text, CultureInfo.InvariantCulture.NumberFormat);
float Ri, B, R, T;
Ri = float.Parse((String.Format("{0:0.00}",textBox2.Text)));
B = float.Parse((String.Format("{0:0.00}",textBox3.Text))));
R = float.Parse((String.Format("{0:0.00}", textBox6.Text)));
T = B / Math.Log(R * 1000 / Ri, Math.Exp(1)) - 273.15;
textBox5.Text = String.Format("{0:0.00}",T);
精彩评论