VB Script Integer division vs Float Division Rounding

时间:2016-06-30 09:56:58

标签: c# asp.net math

Hi Fellow stackoverflowers,

我在将公式从classic asp VBscript转换为C# .net时遇到问题 我需要c#的行为与VBScript

的结果相似

公式就是这样

Dim dTravelHours, result
dTravelHours = 22.7359890666919
result = (CDbl(dTravelHours)*2 + 2)\8

数学上结果是5.9331475但是因为我使用整数除法而不是十进制除法" /"结果是5,我可以通过简单地将结果类型转换为int

来在c#中正确地得到这个结果

但是如果我使用了不同的值:

Dim dTravelHours, result
    dTravelHours = 22.7359890666919
    result = (CDbl(dTravelHours)*2 + 2.5)\8

数学结果为5.9956475 和vbScript结果是6

与5.9456475相同,vbscript结果为6

如何在C#中复制相同的行为? 我已尝试使用Math.Floor, Math.CeilingMath.Round,但仍然没有。

提前感谢您的回答和建议

1 个答案:

答案 0 :(得分:0)

正如MSDN所述,VbScript integer division operato r以这种方式实现:

  

结果是number1除以number2的整数商。该   整数商丢弃任何余数并仅保留整数   一部分。在执行除法之前,将舍入数字表达式   到字节,整数或长子类型表达式。

Round以这种方式实现:它默认返回整数,并将一半舍入到偶数或者银行家的舍入(默认为C#)。

因此,您可以使用Math.Round和整数除法来使用此C#版本:

double value = 22.7359890666919;
double calculationResult1 = value * 2 + 2.0;
double calculationResult2 = value * 2 + 2.5;
double rounded1 = Math.Round(calculationResult1);  // 47
double rounded2 = Math.Round(calculationResult2 ); // 48
int result1 = (int)rounded1 / 8;  // 5
int result2 = (int)rounded2 / 8;  // 6