E.S. E.S. - 1 month ago 8
Java Question

How do I check if a string is convertable to a number

In freemarker, I have a macro

myfunc
that does the following:

<#macro myfunc x>
<#attempt>
<#assign x=(x?number)>
<#recover>
</#attempt>
${x!''}
</#macro>


So, essentially, if
x
(which starts off as a string) and is convertible to a number, then I want to wrap it in
(${x})
otherwise just display the value.

I am fine with this solution except for the ugly
<#attempt>
error logging which comes with it.

There does not seem to be a simple way to check if a string is convertible to a number without using
<#attempt>
or my research is faltering -- I would also rather not do this on the Java side because I see this as view code and doesn't belong with my model code. Anyone know?

Answer

You could use regex:

<#if x?matches("\\d+")>
    // do something with x?number
<#else>
    // do something with x
</#if>
Comments