views:

168

answers:

6

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
+8  A: 

Math.Round Method (Decimal, Int32)

Example:

Math.Round(3.44, 1); //Returns 3.4.
Pranay Rana
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
thanks for the valuable info sir
Pranay Rana
+1  A: 

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

Donnie
A: 

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  A: 

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

Console.WriteLine("{0:0.###}", value);
Matthew Flaschen
A: 

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"
heads5150
A: 

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);
    }
} 
Luís Custódio