Brett
Brett

Reputation: 808

How to check for numeric value in Julia

I want to determine if a value is numeric or not before trying to use a function on it. As a specific example:

z = [1.23,"foo"]
for val in z
    if isnumeric(val)
        round(z)
    end
end

Here isnumeric() is a function that I don't think exists in Julia. I can think of a few different ways this might be done, but I would like to see some suggestions for the "best" way.

Upvotes: 9

Views: 7351

Answers (2)

DNF
DNF

Reputation: 12664

I think the preferred idiom is

isa(val, Number)

Normally you are interested in rounding floats, in which case

isa(val, AbstractFloat)

Upvotes: 16

Michael Ohlrogge
Michael Ohlrogge

Reputation: 10990

You can check the element's type like this:

typeof(val)<:Number

The :< operator checks if a type is a subtype of another.

Here is a very helpful chart giving an overview of numeric types in Julia: https://en.wikibooks.org/wiki/Introducing_Julia/Types

Upvotes: 9

Related Questions