我创建了我的第一个win32表单。我有一个错误,当消息框中显示一个小数作为输出时,它会打印到大约第10个小数位。在控制台程序中,我可以使用precision(2)命令将小数位设置为2个位置,但我无法在win32中找到它。这是代码:
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
if (this->comboBox1->SelectedIndex == 0 && this->radioButton1->Checked == true) {
double a = Convert::ToDouble(this->textBox1->Text->Trim());
double b = Convert::ToDouble(this->textBox2->Text->Trim());
double sum = (b - a) * 100;
MessageBox::Show("$" + sum);
}
else if (this->comboBox1->SelectedIndex == 0 && this->radioButton2->Checked == true) {
double a = Convert::ToDouble(this->textBox1->Text->Trim());
double b = Convert::ToDouble(this->textBox2->Text->Trim());
double sum = (a-b) * 100;
MessageBox::Show("$" + sum);
}
if (this->comboBox1->SelectedIndex == 1 && this->radioButton1->Checked == true) {
double a = Convert::ToDouble(this->textBox1->Text->Trim());
double b = Convert::ToDouble(this->textBox2->Text->Trim());
double sum = (b - a) * 50;
MessageBox::Show("$" + sum);
}
else if (this->comboBox1->SelectedIndex == 1 && this->radioButton2->Checked == true) {
double a = Convert::ToDouble(this->textBox1->Text->Trim());
double b = Convert::ToDouble(this->textBox2->Text->Trim());
double sum = (a - b) * 50;
MessageBox::Show("$" + sum);
}
if (this->comboBox1->SelectedIndex == 2 && this->radioButton1->Checked == true) {
double a = Convert::ToDouble(this->textBox1->Text->Trim());
double b = Convert::ToDouble(this->textBox2->Text->Trim());
double sum = (b - a) * 50;
MessageBox::Show("$" + sum);
}
else if (this->comboBox1->SelectedIndex == 2 && this->radioButton2->Checked == true) {
double a = Convert::ToDouble(this->textBox1->Text->Trim());
double b = Convert::ToDouble(this->textBox2->Text->Trim());
double sum = (a - b) * 50;
MessageBox::Show("$" + sum);
}
}
答案 0 :(得分:1)
如果您想要字符串转换的特定格式,则需要告诉它使用哪种格式。标准数字格式列在MSDN。
为了将double转换为带有两位小数的字符串,您可以使用定点格式。
sum.ToString("F2")
但是,由于您在那里获得了美元符号,因此您转换的价值似乎是美元。在这种情况下,我们可以做得更好,并使用适当的货币格式。这将使用您当前文化的货币符号,或者您可以指定要使用的文化。
sum.ToString("C")