Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleRound a number to the nearest integer or truncate it
Keywordsround off, truncate
CategoriesAlgorithms
 
Use CInt to round to the nearest integer. Use Int to truncate.
 
Private Sub cmdGo_Click()
Dim value As Single
Dim rounded As Integer
Dim truncated As Integer

    value = CSng(txtValue.Text)
    rounded = CInt(value)
    truncated = Int(value)
    lblRounded.Caption = Format$(rounded)
    lblTruncated.Caption = Format$(truncated)
End Sub
 
Note that Int truncates to the next smaller number. If the number is negative, the result is more negative. For example, Int(-17.1) = -18.

Note also that CInt rounds to the nearest even integer for integers plus one half. For example, CInt(16.5) = 16 and CInt(15.5) = 16. It would be better if it always rounded these values up (like most people do) or down, or even if it rounded towards zero. That would make each interval cover the "same" number of values.

The reasoning is that the value could go either way. Rounding to the nearest even value makes it round up half the time and down half the time.

 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated