View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.worksheet.functions
joeu2004[_2_] joeu2004[_2_] is offline
external usenet poster
 
Posts: 829
Default Why is excel rounding my numbers in VBA?

"nappyjim" wrote:
I have a VBA sheet, code seen below. When I input 3 into
a cell, I expect the cell next to it to show 36.88, as the
VBA says. But instead, it rounds its and show 38.

[....]
Function StateAllowance(pVal As String) As Long
Select Case pVal

[....]
Case "3"
StateAllowance = 36.88


In case Claus's solution does not work for you __exactly__ as he wrote (he
made an unrelated and unnecessary change which is presumptuous), the
__minimum__ correction is:

Function StateAllowance(pVal As String) As Double

To answer your question: VBA is rounding 36.88 because you told it to(!).

Type Long is an integer. And VBA rounds non-integers when assigning to an
integer.

If you want VBA to return non-integers, you need to declare StateAllowance
with a non-integer type.

Type Double is a good choice, since that is the type that Excel uses for all
numbers (including integers).