如何解决c#中获取“0”的双模问题

时间:2014-07-03 09:59:59

标签: c# .net casting double modulo

我处于这种情况下,我发现模数为2.0%0.1,这是双变量返回的结果" 0.09999"不是" 0"。

我的代码是:

    var distanceFactor = slider.Value % step; //This do not return 0 when Value=2.0 and step=0.1
    if (distanceFactor != 0)
    {
        slider.Value -= distanceFactor;
    }    
    elseif(distanceFactor == 0)
    {
       //do something here
    }           
    txtblUnits.Text = Math.Round(slider.Value, 1).ToString();

当值= 2.0且步长= 0.1时,如何在elseif条件下获得控件?

4 个答案:

答案 0 :(得分:3)

Modulo %对浮点数没有意义。在应用运算符之前,您应该将它乘以并转换为int。

var distanceFactor = ((int) (slider.Value * 10D)) % (int) (step * 10D);

答案 1 :(得分:1)

您可以在if条件中将距离因子四舍五入为0,如此

if (Math.Round(distanceFactor,0) != 0)
{
    slider.Value -= distanceFactor;
}    
else
{
   //do something here
}

答案 2 :(得分:1)

Double对模数运算符不起作用,因此使用带有浮点数的模数绝不是一个好主意,所以最好使用decimal

decimal slider = 2.0M, step = 0.1M;
var distanceFactor = slider % step; //This will return 0 when Value=2.0 and step=0.1
if (distanceFactor != 0)
{
    slider -= distanceFactor;
}
else if (distanceFactor == 0)
{
    //do something here
}
txtblUnits.Text = Math.Round(slider, 1).ToString();

txtblUnits.Text2.0

答案 3 :(得分:1)

正如我对您的帖子发表评论,为了正确使用模数运算符,请尝试执行以下操作:

string valueDecimalsString = (slider.Value - Math.Floor(slider.Value)).ToString();

int valueDecimals = valueDecimalsString.Substring(valueDecimalsString.IndexOf('.') + 1).Length;

//The same with step

int decimals = (valueDecimals > stepDecimals) ? valueDecimals : stepDecimals;

int value = (int)(slider.Value * Math.Pow(10, decimals))

//the same with step

var distanceFactor = value % stepValue;