CInt vs. Math.Round in Visual Basic .NET - vb.net

What is the difference between:
Dim a As Integer = CInt(2.2)
and
Dim a As Integer = Math.Round(2.2)
?

CInt returns an integer but will round the .5 to nearest even number so:
2 = CInt(2.5)
4 = CInt(3.5)
Are both true, which might not be what you want.
Math.Round can be told to round away from zero. But returns a double, so we still need to cast it
3 = CInt(Math.Round(2.5, MidpointRounding.AwayFromZero))

There is bigger differences in CInt(), Int() and Round()... and others.
Round has parameters of rounding, so it is flexible and user friendly. But it do not change variable type. No "type conversion".
Meanwhile CInt() is a bit cryptic as it rounds too. And it is doing "Type conversion" to integer.
2 = Int(2.555), 3 = CInt(2.555)
2 = Int(2.5), 2 = CInt(2.5)
Some documentation states:
When the fractional part of expression is exactly .5, CInt always rounds it to the nearest even number. For example, .5 rounds to 0, and 1.5 rounds to 2.
But I do not like that "exact 0.5", in real word it is "0.5000001"
So, doing integer math (like calculating bitmaps address Hi and Lo bytes) do not use CInt(). Use old school INT(). Until you get to negative numbers... see the fix() function.
If there is no need to convert type, use floor().
I think all this chaos of number conversion is for some sort of compatibility with some ancient software.

The difference between those two functions is that they do totally different things:
CInt converts to an Integer type
Math.Round rounds the value to the nearest Integer
Math.Round in this instance will get you 2.0, as specified by the MSDN documentation. You are also using the function incorrectly, see the MSDN link above.
Both will raise an Exception if conversion fails, you can use Try..Catch for this.
Side note: You're new to VB.NET, but you might want to try switching to C#. I find that it is a hybrid of VB.NET & C++ and it will be far easier for you to work with than VB.NET.

Related

VB.Net -" console.write(Format((87.20 \ 43.60))) " returning result of 1 not 2, why?

The below line of code is returning as a 1 instead of a 2, for reasons I can't comprehend.
console.write(Format((87.20 \ 43.60)))
Surely this should return the result of 2 but I've checked in another environment and it returns a can anyone tell me why?
I have tried putting the code into a second environment but the result was the same I don't understand why it is returning 1 instead of 2, can anyone enlighten me?
Thanks for the help but found the answer.
Decimals are converted to Long before Integer division and due to this are subject to banker's rounding, multiplying both numbers by a 100 before the operation resolves the issue.
Source of information:
Learn Microsoft - VB.Net - \ Operator - Remarks
Thanks,
While I am glad you resolved your own question, I did want to provide an alternative.
When you use the integer division operator, you do not have control as to how the rounding should occur. Whereas if you do a floating-point division operator you can keep the precision and then use one of the built-in Math class methods (documentation) to specify how the number should round.
Take a look at this example:
Dim result = 87.20 / 43.60
Dim roundUp = Math.Ceiling(result)
Dim roundDown = Math.Floor(result)
Dim bankersRounding = Math.Round(result)
Fiddle: https://dotnetfiddle.net/LZEMXV
Because in your example you are using Console.Write (which treats the data as a String) you do not need to cast the value to an Integer data type. However, if you needed the value as an Integer, any one of those variables outside result can be safely converted to an Integer using the Parse method (documentation).

vb.net divistion wrong outcome

A very weird issue happens when substracting two numbers in vb.net
It returns a wrongful outcome for a very simple math equation :
I am using visual studio 2019
I don't want to use any math.round to fix the value for such simple equation
Any ideas why that issue happens?
Dim diff As Decimal = 100.1 - 100
MsgBox(diff)
it returns 0.0999999999999943
There is a lot more going on in your math than you assume! You have three different primitive types there:
100.1 is a Double
100 is an Integer
diff is a Decimal
If you put Option Strict On at the top of your code, your code will not compile. This will tell you
Option Strict On disallows implicit conversions from 'Double' to 'Decimal'.
So you must either explicitly cast (this is what your Option Strict Off version is doing implicitly)
Dim diff As Decimal = CDec(100.1 - 100)
but since it's the same thing you are already doing implicitly, you will get that same floating point issue. The better thing to do is to start with a Decimal instead of Double in the first place, such as
Dim diff = 100.1D - 100
By using the Decimal literal D at the end of the floating point number it actually does Decimal math, and the result:

math.floor is supposed to return integer

I am trying to get the integer part of a number after dividing two variables.
ie, get 3 if the value is 3.75
displaycount and itemcount are both integer variables.
Dim cntr As Integer
cntr = Math.Floor(Math.Abs(itemCount / displaycount))
That code produces a blue squiggly in VS2012 with the comment that "runtime errors may occur when converting Double to Integer" BUT Math.Floor is supposed to take a decimal or double and return an integer.
"Math.Floor is supposed to take a decimal or double and return an integer." No, it isn't. It returns a value of the same type as its argument. See the documentation, e.g. Math.Floor Method (Double).
I would have expected VS to suggest a fix of adding CInt() around the RHS of the assignment; did that not appear for you?
If you need an Integer as result, consider using either the CInt, Int or the Fix functions.
CInt rounds to the nearest integer using the bankers's rounding (n.5 rounds towards the closest even number).
Int removes the fractional parts. Negative numbers are truncated towards smaller numbers
Int(-8.4) = -9.
Fix removes the fractional parts. Negative numbers are truncated towards greater numbers
Fix(-8.4) = -8.
See Conversion.Int Method and Type Conversion Functions (Visual Basic).

Cleanest way to convert a `Double` or `Single` to `Integer`, without rounding

Converting a floating-point number to an integer using either CInt or CType will cause the value of that number to be rounded. The Int function and Math.Floor may be used to convert a floating-point number to a whole number, rounding toward negative infinity, but both functions return floating-point values which cannot be implicitly used as Integer values without a cast.
Is there a concise and idiomatic alternative to IntVar = CInt(Int(FloatingPointVar));? Pascal included Round and Trunc functions which returned Integer; is there some equivalent in either the VB.NET language or in the .NET framework?
A similar question, CInt does not round Double value consistently - how can I remove the fractional part? was asked in 2011, but it simply asked if there was a way to convert a floating-point number to an integer; the answers suggested a two-step process, but it didn't go into any depth about what does or does not exist in the framework. I would find it hard to believe that the Framework wouldn't have something analogous to the Pascal Trunc function, given that such a thing will frequently be needed when performing graphical operations using floating-point operands [such operations need to be rendered as discrete pixels, and should be rounded in such a way that round(x)-1 = round(x-1) for all x that fit within the range of +/- (2^31-1); even if such operations are rounded, they should use Floor(x+0.5), rather than round-to-nearest-even, so as to ensure the above property]
Incidentally, in C# a typecast from Double to Int using (type)expr notation uses round-to-zero semantics; the fact that this differs from the VB.NET behavior suggests that one or both languages is using its own conversion routines rather an explicit conversion operator included in the Framework. It would seem likely that the Framework should define a conversion operator? Does such an operator exist within the framework? What does it do? Is there a way to invoke it from C# and/or VB.NET?
After some searching, it seems that VB has no clean way of accomplishing that, short of writing an extension method.
The C# (int) cast translates directly into conv.i4 in IL. VB has no such operators, and no framework function seems to provide an alternative.
Usenet had an interesting discussion about this back in 2005 – of course a lot has changed since then but I think this still holds.
You can use the Math.Truncate method.
Calculates the integral part of a specified double-precision floating-point number.
For example:
Dim a As double = 1.6666666
Dim b As Integer = Math.Truncate(a) ' b = 1
I know this is an old case but I saw no one suggest the Math.Round() function.
Yes Math.Round takes a double and returns a double. However it returns a number that has been rounded to a whole number. It should easily and concisely convert to an integer using cInt. Would that suffice?
cInt(math.round(10000.54564)) ' = 10001
cInt(math.round(10000.49564)) ' = 10000
You may need extract the Int part of a float number:
float num = 12.234;
string toint = "" + num;
string auxil = toint.Split('.');
int newnum = Int.Parse(auxil[0]);

What is taking IsNumeric() so long in .NET?

Was doing some benchmarking with IsNumeric today and compared it to the following function:
Private Function IsNumeric(ByVal str As String) As Boolean
If String.IsNullOrEmpty(Str) Then Return False
Dim c As Char
For i As Integer = 0 To Str.Length - 1
c = Str(i)
If Not Char.IsNumber(c) Then Return False
Next
Return True
End Function
I was pretty surprised with the result.
With a numeric value this one was about 8-10 times faster then regular IsNumeric(), and with an empty or non-numeric value it was 1000-1500 times faster.
What is taking IsNumeric so long? Is there something else going on under the hood that I should consider before replacing it with the function above?
I use IsNumeric in about 50 different places all over my site, mostly for validation of forms and query strings.
Where is your check for locale-specific delimiters and decimal places? Negation? Exponential notation?
You see, your function is only a tiny subset of what numeric strings can be.
1,000,000.00
1,5E59
-123456789
You're missing all of these.
A single char can only contains 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
but a full string may contains any of the following:
1
1234
12.34
-1234
-12.34
0001
so IsNumeric ought to be somewhat slower.
There're also cultural and internationalization issues. i.e. If you are processing a Unicode string, does IsNumeric also process numbers from all other languages as well?
Generally speaking, I would avoid duplicating or replacing language features like this, especially in a language like VB, which is bound to be implementing many use cases for you. At the very least, I would name your method something distinct so that it is not confusing to other developers.
The speed difference is bound to be the fact your code is doing far less work than the VB language feature is.
I would use Integer.TryParse() or Double.TryParse() depending on the data type you are using, since both of these account for regional differences.