How can I cast a string to integer for comparison?...
# help
m
How can I cast a string to integer for comparison? Actual usecase: compare a header value "foo" with a integer, and if the value is larger than 100 , then return "Yes", other return "No" I've tried many variations of the following, but it is incorrect (I get a java.lang.ClassCastException):
Copy code
{{#lt request.headers.foo.0 100}}Yes{{else}}No{{/lt}}
l
This is a tricky one and we have had a number of questions about this recently. I think we need a better way of dealing with this type of thing. Depending on the size of the number you are passing in your headers you could compare the header with the string representation of the number like we discussed in this thread - https://wiremock-community.slack.com/archives/C03N1E6HFPY/p1715964959605869 That won't work on larger numbers though.
m
@Lee Turner unfortunately that won't work for me - the number is 20000000. I tried doing string comparisons, but then you get to the situation where "5" > "20000000". Ideally it would be really useful to have a way to cast values into a certain type, but given that's not available, can you think of another solution?
l
OK, this is a little hacky but I think it works. In the latest release (
3.6.0
) we added the
val
helper which allows you to assign a value and maintain its type. The trick here is to do something that converts your header value into an actual int. I think we can use the
math
helper for this. I have just been playing around with a response that looks like this:
Copy code
{{val (math request.headers.foo.0 '-' 0) assign='foo'}}
{
"val":{{foo}},
"text:":"{{#lt foo 20000000}}Yes{{else}}No{{/lt}}"
}
This returns:
Copy code
{
  "val": 100000000,
  "text:": "No"
}
Or:
Copy code
{
  "val": 10000000,
  "text:": "Yes"
}
m
Thanks Lee! This looks like it could work. I’ll try it :).
👍 1