题
public void LoadAveragePingTime()
{
try
{
PingReply pingReply = pingClass.Send("logon.chronic-domination.com");
double AveragePing = (pingReply.RoundtripTime / 1.75);
label4.Text = (AveragePing.ToString() + "ms");
}
catch (Exception)
{
label4.Text = "Server is currently offline.";
}
}
目前我的 label4.Text 得到的是这样的:“187.371698712637”。
我需要它来显示类似的内容:“187.37”
DOT 之后只有两个帖子。有人可以帮我吗?
解决方案
string.Format
是你的朋友。
String.Format("{0:0.00}", 123.4567); // "123.46"
其他提示
如果你想用逗号,你可以使用数学课堂,让您例如循环函数之后仅举两个数字:
float value = 92.197354542F;
value = (float)System.Math.Round(value,2); // value = 92.2;
希望这有助于结果 干杯
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
http://www.csharp-examples.net/string-format-double/
编辑
不知道为什么他们使用“String”而不是“string”,但其余的都是正确的。
double amount = 31.245678;
amount = Math.Floor(amount * 100) / 100;
您可以使用此强>
“的String.Format(”{0:F2} “字符串值);”
// give you only the two digit after Dot, excat two digit.
或者,可以同时使用复合算子f然后指示想要多少小数点小数点后出现。
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568
将上舍入,所以要意识到这一点。
我来源的一般文档。有一吨其他格式运营商那里,以及你可能检查出。
来源: https://msdn.microsoft的.com / EN-US /库/ dwhawy9k(v = vs.110)的.aspx
尝试这个
public static string PreciseDecimalValue(double Value, int DigitsAfterDecimal)
{
string PreciseDecimalFormat = "{0:0.0}";
for (int count = 2; count <= DigitsAfterDecimal; count++)
{
PreciseDecimalFormat = PreciseDecimalFormat.Insert(PreciseDecimalFormat.LastIndexOf('}'), "0");
}
return String.Format(PreciseDecimalFormat, Value);
}
使用String
的属性
double value = 123.456789;
String.Format("{0:0.00}", value);
注意:这可以用来只显示
使用System.Math
double value = 123.456789;
System.Math.Round(value, 2);
尝试这种情况:
double result = Math.Round(24.576938593,2);
MessageBox.Show(result.ToString());
输出:24.57
简单的解决方案:
double totalCost = 123.45678;
totalCost = Convert.ToDouble(String.Format("{0:0.00}", totalCost));
//output: 123.45
yourValue.ToString("0.00") will work.
使用字符串插值decimalVar:0.00
double doublVal = 123.45678;
有两种方法。
为显示在string:
String.Format("{0:0.00}", doublVal );
对歌厅再次双
doublVal = Convert.ToDouble(String.Format("{0:0.00}", doublVal ));
不隶属于 StackOverflow