Question VB6 Round (x, 0)

Something unexpectedly led to unexpected results in my company, and I found this problem:

Dim k As Double Dim r As Integer k = 182.5 r = Round(k,0) 

The result of r is 182, it caused problems in my company, and now I have to fix it.

The fact is that I noticed this:

 Dim k As Double Dim r As Integer k = 186.5 r = Round(k,0) 

r = 187

When the unity of the integer part of double is greater than five, Round does what I expect, but this is not for unities <= 5.

How can I solve this problem? Is there any other function for proper rounding?

+5
source share
2 answers

This is called bankers rounding and tries to distribute rounding up / down by .5 depending on whether the nearest number is odd or even.

To round .5:

 cint(format(182.5, "#0")) ''183 cint(format(186.5, "#0")) ''187 
+6
source

Well, firstly, that’s not how you say it.

 k = 182.5 r = Round(k, 0) 

really produce 182 but

 k = 186.5 r = Round(k, 0) 

will produce 186, not 187, as you mentioned. Now,

 k = 185.5 r = Round(k, 0) 

will also give 186. This is called Rounding Banker and is the standard in VB6. The goal is to cancel the offset, always rounding the exact middle.

If you want to always round 0.5, use

 k = 186.5 r = Int(k * 2 + 1) \ 2 

If you want to always round 0.5 down, you can use something along the line

 k = 186.5 r = Int(k * 2 + 0.99) \ 2 

Add as many nine as the sign digits after the decimal point.

+1
source

Source: https://habr.com/ru/post/1259591/


All Articles