Having a range of numbers on a report instead of each number separated by a comma

Is there a way to have a string of numbers be separated by a hyphen instead of commas when dealing with a range? For example instead of it looking like this: 1, 2, 3, 4, 5, 6 ; it should look like this 1-6 on a report.

Thank you!

Hi @kelshorn!
Assuming the string of numbers will be in a Field in SpiReport, you can use the following Java expression in SpiReport to achieve what you are looking for.

While editing any Expression, you can insert

($F{X}.toString().split(",")[0] + "-" + $F{X}.toString().split(",")[$F{X}.toString().split(",").length - 1].trim())

Just replace X with the name of the field that contains the range in SpiReport!

Please reply if you have any further questions, or if you need the expression refined further!

Things to Note

  • The expression assumes every element is separated by a comma. There may be weird behavior if this is not the case
    • For example, the range 1, 2, 3 5 6 would display as 1-3 5 6
  • The expression works for any list which is separated by commas
    • For example a, b, c, d would display as a-d
  • The expression will work regardless of how many elements are in the range
  • The final result relies only on the first and last element, and nothing in-between
    • 1, a, b, c, e, 4 would display as 1-4

If you’re curious, about how this expression works, here is a brief explanation

What this expression does is “break” and split the range at the , character and converts it to a list of elements.
For example, if given the range (which will be a ‘string’ datatype in Java) 1, 3, 5, 7, 9 we break it into a list with the separate elements 1, 3, 5, 7, 9. The difference is that the string 1, 3, 5, 7, 9 is one element/structure while the list has 5 separate elements/structures (each being one of the numbers, in the order they appear in the string).

With the elements being separated, we tell SpiReport that we want the very first element in this list, then a - character and finally the last element in the list.
Thus the display is always first-last

Thank you for the quick response. I tried this expression and it added the range but instead of it being 1-3, it’s coming out in Specify as 3-3. Do you know why it could be doing this? I checked to make sure the expression was exactly the same and it is.

Thank you,
Kelsey Minatra

I figured out what was going on. I needed the expression to be $V since it’s a variable for that field.

Thanks so much!

Kelsey Minatra

1 Like

I’m glad you found a solution to your problem so quickly!

1 Like