Question: Round Matrix with non-numeric elements

I wrote a procedure which rounds floats to a specified precision. I would like to apply it to a Matrix/List/Array/Vector that contains non-numeric cells as well as floats. I'm stuck at the type-checking stage.


# Round0 works on floats and lists and Matrices of floats:
restart;
Round0 := proc(x,n::integer:=1)
   parse~(sprintf~(cat("%.",n,"f"),x));
end proc:

Round0(1.23456789);
1.2

Round0([1.23456789,9.87654321],2);
[1.23, 9.88]

Round0(phi,2);
Error, (in sprintf) number expected for floating point format

# but fails on non-numeric types.

# #I tried to extend the Round0 procedure with an if clause, but I'm not sure how to apply the rounding only to numeric elements of a list, cells of Matrix, etc..

Round1 := proc(x,n::integer:=1)
   if not type(x,numeric) then return(x);
   else parse~(sprintf~(cat("%.",n,"f"),x)); end if;
end proc:

The above type-checks the whole object, whether a list, a Matrix, etc.. so as soon as one element of the object is non-numeric, the test fails and the rounding is not applied. What's the trick?

Thanks!

Please Wait...