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

Time:01-20

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?

CodePudding user response:

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,

CodePudding user response:

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).

  • Related