31

Possible Duplicate:
How to format a decimal

How can I limit my decimal number so I'll get only 3 digits after the point?

e.g  2.774
Community
  • 1
  • 1
aharon
  • 7,393
  • 10
  • 38
  • 49
  • 5
    for display? or to lose precision even more than you do already with floating point...? – gbn Jul 09 '10 at 12:28

6 Answers6

64

Math.Round Method (Decimal, Int32)

Example:

Math.Round(3.44, 1); //Returns 3.4.
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 11
    Note that by default, C# uses "Banker's Rounding" which may not be what you want, so there is a method overload Math.Round(decimal, int, MidpointRounding) to let you specify exactly which rounding method to use. E.g. TSQL uses 'Away From Zero' rounding so may give a different value than default C# rounding. – Dr Herbie Jul 09 '10 at 12:38
15

I'm assuming you really mean formatting it for output:

Console.WriteLine("{0:0.###}", value);
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • You can also use a [format specifier](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings#the-fixed-point-f-format-specifier): `string result = 1.23456.ToString("F2", CultureInfo.InvariantCulture);` – Matthias Braun Nov 18 '19 at 20:16
8

To get Decimal back use Math.Round with Second parameter specifying number of decimal points.

decimal d = 54.9700M;    
decimal f = (Math.Round(d, 2)); // 54.97

To Get String representation of number use .ToString() Specifiying Decimal Points as N3. Where 3 is the decimal points

decimal d = 54.9700M;    
string s = number.ToString("N3"); // "54.97"
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
heads5150
  • 7,263
  • 3
  • 26
  • 34
1

Use Math.Round to round it to 3 decimal places.

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
Donnie
  • 45,732
  • 10
  • 64
  • 86
1

Limiting the precision of a floating point number is a SQL concept. Decimal in csharp only means that it will remember the precision assigned. You can round to three decimal places before assigning. IE, Math.Round().

Tim Coker
  • 6,484
  • 2
  • 31
  • 62
0

Part of my answer is the response, another part is just a interesting point:

I often want to see the variable as a prop/field. So a create a extension method to solve my problem:

Tensao is just an Enum that have a value related.

    public static class TensaoExtensions {
        public static double TensaoNominal(this Tensao tensao) {
            return Math.Round((double.Parse(EnumMapper.Convert(typeof(Tensao),
                           tensao.ToString()))) * 1000 / Math.Sqrt(3), 3);
        }
    } 
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
Custodio
  • 8,594
  • 15
  • 80
  • 115