102
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?

Martin Brown
  • 24,692
  • 14
  • 77
  • 122
Sergio Tapia
  • 40,006
  • 76
  • 183
  • 254

13 Answers13

197

string.Format is your friend.

String.Format("{0:0.00}", 123.4567);      // "123.46"
Matt Grande
  • 11,964
  • 6
  • 62
  • 89
  • 3
    And again I'm astonished at the speed of this site. Thanks for the help, works great! – Sergio Tapia Aug 18 '09 at 02:29
  • @Steve, yep looks that way! At least you got more rep :P – Matt Grande Aug 18 '09 at 02:41
  • 8
    Yeah, that's why you have 11k. – MrBoJangles Jun 14 '11 at 20:43
  • 5
    this changes the type of the decimal and you need to convert back to decimal again if you want to have a decimal. I think that Math.Round(x, 2) is the better answer if you want to maintain decimal without converting back and forth. Rounding the 3rd digit into 2nd digit also makes sense if it is greater than 5. – Emil Apr 14 '16 at 09:36
  • 2
    Yeah, it depends on what you need. In this case, he needed a string, so that's what I showed. Also, to be clear, `String.Format` handles the rounding the same way `Math.Round` does. – Matt Grande Apr 14 '16 at 13:06
79

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

Martin Brown
  • 24,692
  • 14
  • 77
  • 122
Anas
  • 917
  • 7
  • 6
  • I have float value. so how can I do the same thing. I tried above method but it gives syntax error cannot convert type float to double – Rami Far Apr 27 '17 at 06:22
38
// 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
  • 19,391
  • 1
  • 51
  • 53
  • String is the same as string in C#. I'm not sure why the language has both, but it does. – Matt Grande Aug 18 '09 at 02:32
  • 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 Aug 18 '09 at 02:35
  • 4
    I think that it's preferred style to use String for static function calls – Joe H Aug 18 '09 at 02:36
  • @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 Aug 18 '09 at 02:43
  • How could you have something better than String2, SuperString? and its faster brother SuperAwesomeString? – Yuriy Faktorovich Aug 18 '09 at 02:52
  • 3
    .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 Aug 18 '09 at 11:44
10
yourValue.ToString("0.00") will work.
Sumit Joshi
  • 1,047
  • 1
  • 14
  • 23
9
double amount = 31.245678;
amount = Math.Floor(amount * 100) / 100;
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Miru
  • 91
  • 1
  • 1
  • 3
    Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. (This post was flagged by at least one user, presumably because they thought an answer without explanation should be deleted.) – Nathan Tuggy Apr 30 '15 at 01:24
7

You can use this

"String.Format("{0:F2}", String Value);"

Gives you only the two digits after Dot, exactly two digits.

Milo
  • 3,365
  • 9
  • 30
  • 44
Himanshu Shukla
  • 145
  • 2
  • 1
5

Try this:

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

Output: 24.57

Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85
user3077282
  • 61
  • 1
  • 3
2

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

2

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);
Md. Shafiqur Rahman
  • 2,878
  • 27
  • 24
2

Simple solution:

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

//output: 123.45
Saif
  • 394
  • 3
  • 13
2

double doublVal = 123.45678;

There are two ways.

  1. for display in string:

    String.Format("{0:0.00}", doublVal );
    
  2. for geting again Double

    doublVal = Convert.ToDouble(String.Format("{0:0.00}", doublVal ));
    
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ali Raza
  • 79
  • 1
  • 4
1

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);
        }
Tanmay Nehete
  • 2,138
  • 4
  • 31
  • 42
1

Use string interpolation decimalVar:0.00

emanuel
  • 339
  • 3
  • 7
  • Perhaps there is more you could add to your question, maybe you can explain why this solves the problem, some background on interpolation? – miltonb Jan 05 '17 at 20:08
  • instead using String.Format string interpolation allows easier and more intuitive string formatting. – emanuel Jan 06 '17 at 20:59