且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C#中的两位小数后舍入一个double值

更新时间:2023-09-04 14:22:34

正如其他人指出的那样,正在四舍五入。如果你想在前两个小数字之后删掉数字,你可以这样做:



double y = Math.Floor(value * 100d)/ 100d;



请记住,双打可能会导致精确的准确性问题。您可能需要考虑使用 decimal s。


值18.0051将始终舍入到18.01。要做你想做的事,你可以使用字符串操作:



  double   value  =  18  0051 ; 
string str = value .ToString();
int pos = Math.Min(str.Length,str.IndexOf( )+ 3 );
if (pos > 0
{
str = str.Substring( 0 ,pos);
}
value = Convert.ToDouble(str);





您可以将该代码放入扩展方法中,以便它始终可用。



  public   static   double 截断(  double   value  int 地点)
{
double result = value ;
string str = value .ToString();
int pos = Math.Min(str.Length,str.IndexOf( )+ places + 1 );
if (pos > 0
{
str = str.Substring( 0 ,pos);
}
result = Convert.ToDouble(str);
返回结果;
}





使用新的扩展方法会将外向代码减少到一行:



  double   value  =  18 。 0051 ; 
value = value .Truncate( 2 );


url下面有你的问题的答案



在C#的两位小数中加倍? - 堆栈溢出 [ ^ ]

i need to round my double value after 2 decimal point.
that is 18.0051 to 18.00
but when i tried using math.round it results 18.01
please someone help me

What I have tried:

Math.Round(18.0051, 2, MidpointRounding.AwayFromZero)
Math.Round(18.0051, 2,MidpointRounding.ToEven)

Well as other people point out, it is rounding it. If you are looking to just lop off the digits after first two fractional ones you can do this:

double y = Math.Floor(value*100d)/100d;

Bear in mind that doubles can cause subtle accuracy problems though. You might want to consider using decimals instead.


The value 18.0051 will ALWAYS round to 18.01. To do what you want, you could use string manipulation:

double value = 18.0051;
string str = value.ToString();
int pos = Math.Min(str.Length, str.IndexOf(".") + 3);
if (pos > 0)
{
	str = str.Substring(0, pos);
}
value = Convert.ToDouble(str);



You could put that code into an extension method so it's always available.

public static double Truncate(this double value, int places)
{
    double result = value;
    string str = value.ToString();
    int pos = Math.Min(str.Length, str.IndexOf(".") + places + 1);
    if (pos > 0)
    {
        str = str.Substring(0, pos);
    }
    result = Convert.ToDouble(str);
    return result;
}



Using the new extension method would reduce your outward facing code to a single line:

double value = 18.0051;
value = value.Truncate(2);


Below url has answer for your question

Round double in two decimal places in C#? - Stack Overflow[^]