86
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 之后只有两个帖子。有人可以帮我吗?

4

13 回答 13

178

string.Format是你的朋友。

String.Format("{0:0.00}", 123.4567);      // "123.46"
于 2009-08-18T02:26:05.600 回答
68

如果您只想在逗号后取两个数字,则可以使用为您提供 round 函数的数学类,例如:

float value = 92.197354542F;
value = (float)System.Math.Round(value,2);         // value = 92.2;

希望这
有帮助

于 2013-04-30T15:55:05.900 回答
36
// 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”,但其余的都是正确的。

于 2009-08-18T02:26:49.657 回答
10
yourValue.ToString("0.00") will work.
于 2018-03-16T12:51:52.047 回答
8
double amount = 31.245678;
amount = Math.Floor(amount * 100) / 100;
于 2015-04-29T19:35:52.537 回答
6

你可以用这个

"String.Format("{0:F2}", 字符串值);"

仅给您 Dot 之后的两位数,即两位数。

于 2015-07-14T17:12:52.400 回答
4

尝试这个:

double result = Math.Round(24.576938593,2);
MessageBox.Show(result.ToString());

输出:24.57

于 2017-01-13T10:27:57.903 回答
2

或者,您也可以使用复合运算符 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/library/dwhawy9k(v=vs.110).aspx

于 2015-07-12T20:24:54.733 回答
2

使用的属性String

double value = 123.456789;
String.Format("{0:0.00}", value);

注意:这只能用于显示。

使用System.Math

double value = 123.456789;
System.Math.Round(value, 2);
于 2016-06-23T16:42:44.963 回答
2

简单的解决方案:

double totalCost = 123.45678;
totalCost = Convert.ToDouble(String.Format("{0:0.00}", totalCost));

//output: 123.45
于 2017-06-03T17:13:51.470 回答
2

double doublVal = 123.45678;

有两种方法。

  1. 在字符串中显示:

    String.Format("{0:0.00}", doublVal );
    
  2. 再次获得双倍

    doublVal = Convert.ToDouble(String.Format("{0:0.00}", doublVal ));
    
于 2019-05-16T12:00:00.703 回答
1

使用字符串插值decimalVar:0.00

于 2017-01-05T17:55:22.817 回答
1

尝试这个

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);
        }
于 2015-12-03T09:58:59.343 回答