views:

675

answers:

2
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.34"

Only two posts after the DOT. Can someone help me out?

+3  A: 

string.Format is your friend.

String.Format("{0:0.00}", 123.4567);      // "123.46"
Matt Grande
You Googled the same place, but didn't give it credit. :-)
Steven Sudit
And again I'm astonished at the speed of this site. Thanks for the help, works great!
Sergio Tapia
@Steve, yep looks that way! At least you got more rep :P
Matt Grande
Don't really care about the rep, but thanks.
Steven Sudit
+6  A: 
// 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.

Steven Sudit
Thanks, helped a lot!
Sergio Tapia
String is the same as string in C#. I'm not sure why the language has both, but it does.
Matt Grande
Which to use is a good question. What will happen if string is later mapped to a faster String2 class? Will that class have the same Format method?
Yuriy Faktorovich
I think that it's preferred style to use String for static function calls
Joe H
@Yuriy - We'll cross that bridge when we have to deal with a faster String2 class (that I certainly hope has a better name)
Matt Grande
How could you have something better than String2, SuperString? and its faster brother SuperAwesomeString?
Yuriy Faktorovich
.Net has System.String, or String for short. C# has string, a native type that maps to System.String. You can use one in the place of the other, but when programming C#, there's no reason to use the non-C# name, not even in statics. Of course, due to common FormatWith extension methods, the question of whether to capitalize string for static calls becomes less relevant.
Steven Sudit