numberFormat affecting array keys???

Mark Waddingham mark at livecode.com
Fri Apr 21 03:26:19 EDT 2017


On 2017-04-21 01:51, Bob Sneidar via use-livecode wrote:
> Put this into a button:
> 
> on mouseUp
>    set the numberFormat to "00"
>    repeat with i=1 to 10
>       put i into myArray [i]
>       breakpoint
>    end repeat
> end mouseUp
> 
> At the breakpoint examine the array. There will be a 1 in an element
> with the name... ready??? "01"
> 
> Okay THAT has GOT to be a bug!!! Why the hell is numberformat
> modifying the name of the array element?? I haven't done ANY math on
> it. Apparently the engine DOES!

As others have already said, this isn't a bug - just a consequence of
the rules previously mentioned. The engine is doing this:

   repeat with i = strToNum(1) to strToNum(10)
     put i into myArray[numToStr(i)]
   end repeat

So, the value of the key is put into the array as a number but array
keys are always strings, so it is converted to a string before indexing
the array.

I think this is perhaps more evidence that 'numberFormat' should 
probably
be deprecated - or at least marked as 'present for HyperCard 
compatibility
only and shouldn't be used in new code'.

Indeed, even the latter is somewhat misleading as (due to the IEEE 
double
internal representation used for numbers in LiveCode), numberFormat does
not and cannot work the same.

(The reason it cannot work the same is that the numberFormat expresses
precision in decimal places, but doubles use binary representation - so
a double can only approximate a decimal number to a certain number of
decimal places, it can't faithfully represent it except for a subset
of values).

My general recommendation is:

   1) Don't use numberFormat in new code.

   2) Use format() to format your numbers *when you want to display 
them*.

   3) Use round() to control the precision of your numbers.

Warmest Regards,

Mark.

-- 
Mark Waddingham ~ mark at livecode.com ~ http://www.livecode.com/
LiveCode: Everyone can create apps




More information about the use-livecode mailing list