ASP/VBScript - Int() vs CInt()

2019-03-17 13:09发布

问题:

What is the difference in ASP/VBScript between Int() and CInt()?

回答1:

  • Int()

The Int function returns the integer part of a specified number.

  • CInt()

The CInt function converts an expression to type Integer.

And the best answer comes from MSDN

CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.



回答2:

And, the most important difference (IME, at least)....is that CInt overflows at 32,767.



回答3:

Here is another difference:

Script:

wscript.echo 40.91 * 100
wscript.echo Int(40.91 * 100)
wscript.echo CInt(40.91 * 100)

result:

4091
4090   (????)
4091

Any thoughts?



回答4:

The usual answer for this issue is to manually force a re-rounding. This problem is as old as FORTRAN.

Instead of

a = int(40.91 * 100)

Use

b = 40.91 * 100
a = int(b + 0.5)

Very old trick, still useful in Excel spreadsheets from time to time.