How to limit a decimal number? [duplicate]

孤街醉人 提交于 2019-12-18 07:31:16

问题


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

回答1:


Math.Round Method (Decimal, Int32)

Example:

Math.Round(3.44, 1); //Returns 3.4.



回答2:


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

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



回答3:


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"



回答4:


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().




回答5:


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




回答6:


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);
        }
    } 


来源:https://stackoverflow.com/questions/3212491/how-to-limit-a-decimal-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!