locked
How do I round a number to nearest .5

    Question

  • I have a formula in my program which returns values such as 4.67.  I would like it to round that value to the nearest .5.  In this example, I would like a return value of 4.5.  Does anyone know how to do this?  I am not very familiar with the Round functions.  Thanks a bunch.

    Melissa

    CY = (TextBoxDepth.Text / 12) * (TextBoxLength.Text * TextBoxWidth.Text) / 27

    CYR = Math.Round(CY, 1) - not sure what to put here?

    Sunday, April 23, 2006 7:33 PM

Answers

  • Melissa,

    I don't think Math.Round will get you the answer that you want. First the variable CY must be typed as Decimal. Then the second parameter will round the number to a number of decimal digits; Math.Round(4.67D, 1) = 4.7.

    I suggest rolling your own function.  Try this:

    Dim CY, CYR As Single
    CYR = (Math.Floor(2 * (CY + 0.25))) / 2

    Monday, April 24, 2006 1:52 AM

All replies

  • Melissa,

    I don't think Math.Round will get you the answer that you want. First the variable CY must be typed as Decimal. Then the second parameter will round the number to a number of decimal digits; Math.Round(4.67D, 1) = 4.7.

    I suggest rolling your own function.  Try this:

    Dim CY, CYR As Single
    CYR = (Math.Floor(2 * (CY + 0.25))) / 2

    Monday, April 24, 2006 1:52 AM
  • Thanks so much.  The function worked great.  I realized after I posted that I need to use Decimal.  Could you explain 'single' to me?  I took a class in VB5.0 years ago, but am very rusty - just getting back to it.  I know math.floor rounds everything down, but how did you figure to add .25, multiply by 2, round it down, then divide by 2?  I know it's late, but my brain is having a hard time wrapping itself around that!

    Melissa

    Monday, April 24, 2006 3:15 AM
  • Melissa,

    You're welcome.  Single is a variable type like Integer and String, but it declares variables that are numbers with a decimal part.  Unlike the Decimal type the representation is in binary.  Like 4.67.  I'm a VB newbe, but a math whiz.  It is late so instead of going through a long explaination consider how to round a number to the tens place. 

    Round 3.47 = (Int(10 * 3.47 +0. 5))/10
    Round 3.47 = (Int(34.7 +0.5))/10
    Round 3.47 = (Int(35.2))/10
    Round 3.47 = (35)/10
    Round 3.47 = 3.5

    Monday, April 24, 2006 4:09 AM