Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if a variant created from a string is a whole number?

I am looking to determine if a variant created from a string is a whole number.

Here's a test script:

dim v as variant
v = "42"
if v <> round(v) then
    msgBox("<>")
end if

The msgBox pops up, probably because the variant was created from a string, although I would have expected v to be = round(v).

like image 726
René Nyffenegger Avatar asked Nov 25 '09 08:11

René Nyffenegger


People also ask

How do you check if a number is a whole number in VB?

1, First check if the string value is numeric. 2, Compare the floor and ceiling of the number. If it's the same, you have a whole number.

What is a Variant data type?

The Variant data type is the data type for all variables that are not explicitly declared as some other type (using statements such as Dim, Private, Public, or Static).

How do you define a Variant in VBA?

VBA Variant Doesn't Require Explicit Way The general procedure to declare a VBA variable is to first name the variable and then assign the data type to it. Below is an example of the same. This is the explicit way of declaring the variable.


1 Answers

You should write something like:

if cDbl(v) <> round(cDbl(v)) Then

Where cDbl is a function converting any data to a double-type number. You might have to treat cases where v cannot be converted to a number with the isNumeric() function before calling the cDbl function. You can even use the cInt function for your comparisons:

if isnumeric(v) then
    if cDbl(v) - cInt(v) <> 0 Then
    ....
    endif
else
   debug.print "data cannot be converted to a number"
endif
like image 168
Philippe Grondier Avatar answered Sep 22 '22 19:09

Philippe Grondier