如何在C#中的两位小数后舍入一个double值 [英] How do I round a double value after two decimal place in C#

查看:240
本文介绍了如何在C#中的两位小数后舍入一个double值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在2位小数点后舍入我的双倍值。

即18.0051到18.00

但是当我尝试使用math.round时它会得到18.01
请有人帮助我



我尝试过:



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

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

解决方案

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



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  = < span class =code-digit> 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[^]


这篇关于如何在C#中的两位小数后舍入一个double值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆