四舍五入到最接近的.00或.05,而不是小数中的.01或.02等



我在尝试对十进制价格进行四舍五入的地方进行了舍入,以便小数始终舍入到.00或.05(使用此规则.00、.01、.02、.03、.04=.00和.05、.06、.07、.08、.09=.05(-但现在使用下面的代码,它也会在十进制数中返回.01、.02等。

// 2 is the number of decimals that it should return.
decimal unitPriceFloored = System.Math.Round(price, 2, System.MidpointRounding.ToZero);

我如何更改它,使其将价格四舍五入到小数点中的.00或.05?只是为了澄清一下——这应该与.10和.15等(都是2个十进制逗号(的工作方式相同

我不知道有什么内置函数可以做到这一点。这里有一种方法:

for(decimal m = 1m; m < 1.2m; m = m + 0.01m)
WriteLine( $"{m} -> {Math.Truncate(m) + (int)(((m - Math.Truncate(m))*100)/5) * 0.05m }");

此打印:

1 -> 1.00 
1.01 -> 1.00
1.02 -> 1.00
1.03 -> 1.00
1.04 -> 1.00
1.05 -> 1.05
1.06 -> 1.05
1.07 -> 1.05
1.08 -> 1.05
1.09 -> 1.05
1.10 -> 1.10
1.11 -> 1.10
1.12 -> 1.10
1.13 -> 1.10
1.14 -> 1.10
1.15 -> 1.15
1.16 -> 1.15
1.17 -> 1.15
1.18 -> 1.15
1.19 -> 1.15

这应该有效:

decimal  cal   ( decimal d )
{
decimal num =  d;
decimal or =  digits(  num); 

if (or >= .05m)  return (num - or) + .05m ; 
return   num -or;
}


decimal  digits   (   decimal  x )
{ while( x >  1000 )
{
x-=1000; 
}
while ( x >100)
{
x-=100; 
}
while(x > 10)
{
x -= 10; 
}
while (   x   >= 1   )
{
x--; 
}
return subdigits (x) ; 
}    
decimal subdigits( decimal some)
{

while ( some  >=  0.1m )
{
some   -=.1m ;
}
return  some ;
}

附言:还是要习惯stackoverflow格式,对不起。。。结果如下:
1->1
1.01->1.0
1.02->1
1.03->1
1.04->1

1.05->1.05
1.06->1.05
1.07->1.05
1.08->1.05
1.09->1.05
1.1-<1.1
2->2
现在它应该工作了:D

最新更新