Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Parse a string to a number safely
ResourceFunction["NumberParse"]["string"] parses string to an integer or real number. |
"AllowPrecision" | False | whether to parse numbers specified with arbitrary precision |
"AllowScientificNotation" | False | whether to parse numbers specified in scientific notation |
"AllowNonDecimal" | False | whether to parse numbers specified in bases other than base 10 |
Parse an integer:
In[1]:= | ![]() |
Out[1]= | ![]() |
Parse a real number:
In[2]:= | ![]() |
Out[2]= | ![]() |
Parse a negative number:
In[3]:= | ![]() |
Out[3]= | ![]() |
$Failed will be returned if the string could not be parsed safely:
In[4]:= | ![]() |
Out[4]= | ![]() |
NumberParse threads automatically over lists:
In[5]:= | ![]() |
Out[5]= | ![]() |
Arbitrary-precision numbers cannot be parsed with default settings:
In[6]:= | ![]() |
Out[6]= | ![]() |
Enable parsing of arbitrary-precision numbers:
In[7]:= | ![]() |
Out[7]= | ![]() |
Numbers specified in scientific notation do not parse by default:
In[8]:= | ![]() |
Out[8]= | ![]() |
Enable parsing of numbers specified in scientific notation:
In[9]:= | ![]() |
Out[9]= | ![]() |
Numbers specified in bases other than 10 do not parse by default:
In[10]:= | ![]() |
Out[10]= | ![]() |
Enable parsing of non-decimal numbers:
In[11]:= | ![]() |
Out[11]= | ![]() |
ToExpression can also be used to parse numbers, but is dangerous to use with unfiltered input:
In[12]:= | ![]() |
Out[12]= | ![]() |
In[13]:= | ![]() |
NumberParse filters its input, evaluating only numeric content judged to be safe:
In[14]:= | ![]() |
Out[14]= | ![]() |
FromDigits can also be used to safely parse numbers, but it only supports non-negative integers:
In[15]:= | ![]() |
Out[15]= | ![]() |
In[16]:= | ![]() |
Out[16]= | ![]() |
In[17]:= | ![]() |
Out[17]= | ![]() |
NumberParse supports real and negative numbers:
In[18]:= | ![]() |
Out[18]= | ![]() |
In[19]:= | ![]() |
Out[19]= | ![]() |
Interpreter["Number"] can also be used to safely parse numbers, but its performance can be unpredictable. By contrast, NumberParse has relatively stable, reasonably fast performance:
In[20]:= | ![]() |
Out[20]= | ![]() |
NumberParse does not support complex or rational numbers:
In[21]:= | ![]() |
Out[21]= | ![]() |
This work is licensed under a Creative Commons Attribution 4.0 International License