问题
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.\";
}
}
Currently my label4.Text get\'s something like: \"187.371698712637\".
I need it to show something like: \"187.37\"
Only two posts after the DOT. Can someone help me out?
回答1:
string.Format is your friend.
String.Format("{0:0.00}", 123.4567); // "123.46"
回答2:
If you want to take just two numbers after comma you can use the Math Class that give you the round function for example :
float value = 92.197354542F;
value = (float)System.Math.Round(value,2); // value = 92.2;
Hope this Help
Cheers
回答3:
// 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/
edit
No idea why they used "String" instead of "string", but the rest is correct.
回答4:
double amount = 31.245678;
amount = Math.Floor(amount * 100) / 100;
回答5:
You can use this
"String.Format("{0:F2}", String Value);"
Gives you only the two digits after Dot, exactly two digits.
回答6:
Using the property of String
double value = 123.456789;
String.Format("{0:0.00}", value);
Note: This can be used to display only.
Using System.Math
double value = 123.456789;
System.Math.Round(value, 2);
回答7:
Try this:
double result = Math.Round(24.576938593,2);
MessageBox.Show(result.ToString());
Output: 24.57
回答8:
yourValue.ToString("0.00") will work.
回答9:
Alternatively, you may also use the composite operator F then indicating how many decimal spots you wish to appear after the decimal.
string.Format("{0:F2}", 123.456789); //123.46
string.Format("{0:F3}", 123.456789); //123.457
string.Format("{0:F4}", 123.456789); //123.4568
It will round up so be aware of that.
I sourced the general documentation. There are a ton of other formatting operators there as well that you may check out.
Source: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
回答10:
Try This
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);
}
回答11:
Simple solution:
double totalCost = 123.45678;
totalCost = Convert.ToDouble(String.Format("{0:0.00}", totalCost));
//output: 123.45
回答12:
Use string interpolation decimalVar:0.00
回答13:
double doublVal = 123.45678;
There are two ways.
for display in string:
String.Format("{0:0.00}", doublVal );for geting again Double
doublVal = Convert.ToDouble(String.Format("{0:0.00}", doublVal ));
来源:https://stackoverflow.com/questions/1291483/leave-only-two-decimal-places-after-the-dot