[Tex/LaTex] Checking for valid floating point number

floating pointpgfmath

I want to do the following: I am generating a report which can be set to be in imperial or metric units. All values are originally in metric units, so in the case of imperial units all values should be converted. Some values can be say N/A or any other string value, in case the value is not applicable. The document is automatically generated. For conversion I am using the fp package, but the challenge is the checking the input. The fp package (and pgfmath) will ofcourse) err if you try to do math with non-numerical values.
This is what I currently have (only works for integer input)

% Convert meters to inches
\newcommand{\convertmtoin}[2]
{
    \if!\ifnum9<1#1!\else_\fi   
    \FPeval{val}{#1*39.3700787} \FPround{\val}{\val}{#2}
    \else
    \def\val{#1}
    \fi
}

Using pgfmath one could do something like this

\newcommand{\convertmtoin}[2]
{
    \pgfmathfloatparsenumber{#1}
    \pgfmathfloatifflags{\pgfmathresult}{3}{\FPeval{val}{#1*39.3700787} \FPround{\val}{\val}{#2}}{\def\val{#1}} 
}

But I am not able to set the error handler of pgfmath to output NaN in the case of erronous input to pgfmathfloatparsenumber

\pgfkeys{/pgf/fpu/handlers/invalid number={??}{??}}

Thanks for any help!

Best Answer

You can also use \IfDecimal from the xstring package:

enter image description here

Code:

\documentclass{article}
\usepackage{xstring}

\newcommand*{\CheckIfNumerical}[1]{%
    \IfDecimal{#1}{%
        ``#1" is a number.%
    }{%
        ``#1" is NOT a number.%
    }%
}%


\begin{document}
\par\CheckIfNumerical{7}
\par\CheckIfNumerical{3.14}
\par\CheckIfNumerical{NaN}
\par\CheckIfNumerical{7. 0}
\par\CheckIfNumerical{7.0X09}
\end{document}
Related Question