Tech Tip: Quirks of the LOCATE Statement
When I ran across this blog post a month or so ago, I thought it was worth republishing, as many of us have run into this one time or another.
The LOCATE statement is one of the most commonly used Basic statements in our MultiValue enterprise software. With it's ability to find exact matches easily, as well as providing basic right and left justification sorts, it saves a lot of time and coding.
Although, since it is designed to be used with strings, sometimes it does odd things with decimal numbers. See the example in Figure 1.
array='' list.array = 4.5 :@VM: 21 :@VM: 8.1 :@VM: 32 :@VM: 70 FOR v = 1 TO 5 LOCATE(list.array<1,v>,array,1;position;'ar') THEN NULL array = INSERT(array,1,position;list.array<1,v>) NEXT v * FOR a = 1 TO 5 PRINT array<1,a> :"-": NEXT a Output: 21-32-4.5-70-8.1
You will notice that the output didn't place the 4.5 and 8.1 in the correct order.
There is an easy fix, though: Make sure that your numbers are always in internal format. In other words, you need to remove the decimal point from data (figure 2)
array ='' list.array = 4.5 :@VM: 21 :@VM: 8.1 :@VM: 32 :@VM: 70 FOR v = 1 TO 5 VALUE = ICONV(list.array<1,v>,"MD2") LOCATE(VALUE,array,1;position;'ar') THEN NULL array = INSERT(array,1,position;VALUE) NEXT v * FOR a = 1 TO 5 PRINT OCONV(array<1,a>,"MD2") :"-": NEXT a OUTPUT 4.5-8.1-21-32-70
As you can see the data in is now in the correct order. You are not limited to an MD2 (MR2). You can use MD4 (MR4), or you can multiply and divide by 1000 to remove the decimals, but be careful of your PRECISION settings, as it may generate odd results.
You can see the original blog posting via the shortlink: http://intl-spectrum/s1033