如何在C#windows应用程序中计算百分比 [英] How to calculate percentage in C# windows application
本文介绍了如何在C#windows应用程序中计算百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想计算百分比,我已经完成但无法以我想要的格式获取价值。
假设我正在计算以下
(579803.4 * 14%)= 81,172.476
但计算后我想要81,172.48。我该怎么办?
预先谢谢
我尝试过:
textBox1.Text =(((float.Parse(textBox2.Text))*(float.Parse(textBox3。文本))/ 100))。ToString();
I want to calculate percentage, and I have done it but unable to get value in which format I want.
suppose I am calculating following
(579803.4 * 14%)=81,172.476
but I want to 81,172.48 after calculation. what should I do?
Thanks In advance
What I have tried:
textBox1.Text = (((float.Parse(textBox2.Text)) * (float.Parse(textBox3.Text)) / 100)).ToString();
推荐答案
尝试
Try
textBox1.Text = (((float.Parse(textBox2.Text)) * (float.Parse(textBox3.Text)) / 100)).ToString("F2");
首先,不要在用户输入上使用Parse:请改用TryParse:
First off, don't use Parse on user input: use TryParse instead:
double d1, d2;
if (!double.TryParse(textBox2.Text, out d1))
{
MessageBox.Show(string.Format("{0} is not a number", textBox2.Text));
return;
}
if (!double.TryParse(textBox3.Text, out d2))
{
MessageBox.Show(string.Format("{0} is not a number", textBox3.Text));
return;
}
textBox1.Text = (d1 * d2 / 100).ToString("#.00");
这样,如果您的用户输入错误,您的应用就不会崩溃......
That way, your app won't crash if your user misskeys...
使用
ToString(0.00); // 2dp数字
或
Math.Round(yourAmount,2)
为2位小数。
Use
ToString("0.00"); //2dp Number
Or
Math.Round(yourAmount,2)
for 2 decimal.
这篇关于如何在C#windows应用程序中计算百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文