test if string can be converted to a number in FreeMarker

给你一囗甜甜゛ 提交于 2021-01-27 07:20:27

问题


I am trying to test whether a string can be converted into a number in FreeMarker. For example, "123" and "3.14" can be converted, but "foo" can't. I know that I can test for this by using the number method on the string (e.g. "123"?number) and seeing whether it produces an error, but I am looking for a way to test for this without causing an error.

I tried ?matches("^\d+$"), and it works fine for integers, but I am looking for something that works on all numbers.

I can probably do it using a more sophisticated regex, but I am wondering if there is a simpler way.


回答1:


The simpler way is to not do it in FreeMarker :-) This sounds like something controller (or method on model) should be doing rather than view template. That said, you have a few options:

  1. Use ?number built-in within <#attempt> / <#recover> block.
  2. Write a method in one of your model objects to check whether your string into a number and invoke it from the template.
  3. Write a custom directive to do this for you.


来源:https://stackoverflow.com/questions/1474274/test-if-string-can-be-converted-to-a-number-in-freemarker

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!