I imported a table in mathematica using Import["..file","table"] now I cant use the numbers in the table as they are in string formta, can someone please explain how can i convert them from string to number again?
2 Answers
Another approach is to use Read
. This is useful if you have numbers in "E" form scientific notation:
Read[StringToStream[#], Number] &/@{ "1" ,"1.5" , "1E-20" , "2.E10" }
{1, 1.5, 1.5*10^-20, 2.*10^10}
Note ToExpression
gets these wrong:
ToExpression /@ {"1", "1.5", "1.5E-20", "2.E10"}
{1, 1.5, -15.9226, 2. E10}
"1.5E-20" is evaluated as 1.5 * 2.71828-20 in the last case the "E10" is taken as a new symbol..
ToExpression
is however faster if you can use it..
Edit...per comment StringToStream
leaves the streams open. This closes the streams:
stringToNumber[s_String] :=
Module[{str = StringToStream@s, n}, n = Read[str, Number]; Close@str; n]
stringToNumber /@ {"1", "1.5", "1E-20", "2.E10"}
-
-
ToExpression should never be used on user input, as it can execute arbitrary code: it's a huge unnecessary security risk.– JamesCommented Feb 14, 2023 at 16:38
-
1Note, that this opens as many streams as the numbers you have (check with
Streams[]
) that are not closed. Commented Oct 17, 2023 at 13:29 -
The intrinsic function ToExpression
will convert its argument to an expression; if the argument is the string representation of a number the function will return the number.
These days (early 2023) there are other ways to convert a number string to a number. For example
Interpreter["Number"]["4.1234"]
ought to return the number 4.1234
, and ought to fail when the string can't be parsed as a number. This approach makes it more difficult for arbitrary code to execute.
-
3This method has the potential to execute arbitrary code if taking input from an untrusted source. Commented Sep 26, 2019 at 16:39
-
Yes, evaluating a totally general expression to get a number is an insane and unnecessary security risk. Crazy that there is not an in-built function to convert a string to a number!– JamesCommented Feb 14, 2023 at 16:35
Import[.."Table"]
should handle numbers correctly to begin with. Can you show what the file looks like?