Fufu Alex
Fufu Alex

Reputation: 37

C# Display 2 decimal places

I cant figure out how to display 2 decimal within this code. Below is a code show when i chose the option from combobox1 and combobox2 then i key any value to textbox2, so it will store the new value. And also if i chose back the same option from combobox1 and combobox2 it will auto take 1/textBox2.Text. But i want to display only 2 decimal places. Can anyone help out with this code?

Thanks

            int index1 = comboBox1.SelectedIndex;
            int index2 = comboBox2.SelectedIndex;
            arr[index1, index2] = double.Parse(textBox2.Text);
            arr[index2, index1] = (1 / double.Parse(textBox2.Text));       
            MessageBox.Show("Your Current Rate Have Been Updated"); 

Upvotes: 0

Views: 10073

Answers (2)

terrybozzio
terrybozzio

Reputation: 4542

I think this will provide you with the result with 2 decimal places:

arr[index1, index2] = Convert.ToDouble(string.Format("{0:0.00}", double.Parse(textBox2.Text)));
arr[index2, index1] = Convert.ToDouble(string.Format("{0:0.00}", (1 / double.Parse(textBox2.Text))));

This is for your specific code but like others pointed out if its money for better rounding would be better decimal,and the use of Math class.

Upvotes: 2

DonBoitnott
DonBoitnott

Reputation: 11025

This should help:

int index1 = comboBox1.SelectedIndex;
int index2 = comboBox2.SelectedIndex;
arr[index1, index2] = String.Format("{0:N2}", double.Parse(textBox2.Text));
arr[index2, index1] = String.Format("{0:N2}", 1 / double.Parse(textBox2.Text)));
MessageBox.Show("Your Current Rate Have Been Updated"); 

Look here for the full list of Standard Numeric Format Strings.

Upvotes: 5

Related Questions