How do you round a number to two decimal places in C#?

后端 未结 15 1028
挽巷
挽巷 2020-11-22 08:59

I want to do this using the Math.Round function

相关标签:
15条回答
  • 2020-11-22 09:44
      public double RoundDown(double number, int decimalPlaces)
            {
                return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces);
            }
    
    0 讨论(0)
  • 2020-11-22 09:45

    // convert upto two decimal places

    String.Format("{0:0.00}", 140.6767554);        // "140.67"
    String.Format("{0:0.00}", 140.1);             // "140.10"
    String.Format("{0:0.00}", 140);              // "140.00"
    
    Double d = 140.6767554;
    Double dc = Math.Round((Double)d, 2);       //  140.67
    
    decimal d = 140.6767554M;
    decimal dc = Math.Round(d, 2);             //  140.67
    

    =========

    // just two decimal places
    String.Format("{0:0.##}", 123.4567);      // "123.46"
    String.Format("{0:0.##}", 123.4);         // "123.4"
    String.Format("{0:0.##}", 123.0);         // "123"
    

    can also combine "0" with "#".

    String.Format("{0:0.0#}", 123.4567)       // "123.46"
    String.Format("{0:0.0#}", 123.4)          // "123.4"
    String.Format("{0:0.0#}", 123.0)          // "123.0"
    
    0 讨论(0)
  • 2020-11-22 09:46

    I know its an old question but please note for the following differences between Math round and String format round:

    decimal d1 = (decimal)1.125;
    Math.Round(d1, 2).Dump();   // returns 1.12
    d1.ToString("#.##").Dump(); // returns "1.13"
    
    decimal d2 = (decimal)1.1251;
    Math.Round(d2, 2).Dump();   // returns 1.13
    d2.ToString("#.##").Dump(); // returns "1.13"
    
    0 讨论(0)
  • 2020-11-22 09:47

    One thing you may want to check is the Rounding Mechanism of Math.Round:

    http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx

    Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.

    0 讨论(0)
  • 2020-11-22 09:47

    string a = "10.65678";

    decimal d = Math.Round(Convert.ToDouble(a.ToString()),2)

    0 讨论(0)
  • 2020-11-22 09:48

    This is for rounding to 2 decimal places in C#:

    label8.Text = valor_cuota .ToString("N2") ;
    

    In VB.NET:

     Imports System.Math
     round(label8.text,2)
    
    0 讨论(0)
提交回复
热议问题