Generates an integer
set b to random number from 0 to 6
--> 3
Generates a real
set b to (random number from 0 to 6 as string)
--> 3.456827096814
However, if you separate with parentheses, then you get an integer as a string:
set b to ((random number from 0 to 6) as string)
--> "1"
I’m guessing that this is the issue (from the Commands Reference):
If at least one limit is specified, and all specified limits are integers, the result is an integer. Otherwise, the result is a real, and may have a fractional part.
By making it into a string as part of the generation, at least one of the specified limits was a string (and thus, not an integer). That’s how I read it, anyway.
Regarding your prior post (#19 I think), sorry but I didn’t read your earlier post until later.
Line 1 of the script creates a random number between 0 and 60000000. Line 2 does the following:
- concatenates (joins) “0000000” and the random number from line 1 of the script;
- takes the last 8 characters of the string created in step 1;
- concatenates “07” and the string created in step 2.
For example, if the random number created in line 1 of the script is 999 then:
- “0000000” & 999 → “0000000999”
- text -8 thru -1 of “0000000999” → “00000999”
- “07” & “00000999” → “0700000999”
BTW in line 2 of the script I put unnecessary parentheses around “00000000”
The way ‘random number’ works is:
• It it’s used without parameters, it returns a real between 0.0 and 1.0 inclusive.
• If it’s used with a direct number parameter (random number n), it returns a number between 0 and n inclusive. If n’s an integer, the returned number’s an integer, otherwise it’s a real.
• If it’s used with ‘from’ and ‘to’ parameters, it returns a number between the two parameter values inclusive. If both values are integers, the result’s an integer. Otherwise the result’s a real.
(random number from 0 to 6 as string) is the same as random number from 0 to (6 as string), since there’s nothing separating the as string from the to value. Although the “6” is automatically coerced to number (probably an integer) during the execution of ‘random number’, its original class isn’t integer as far as ‘random number’ is concerned and so a real is returned. In your code, the real isn’t coerced to string until it’s concatenated to “0”. To get the result you actually want, you have to bracket the whole of the ‘random number’ command off from the ‘as string’ so that it’s the result that’s coerced, not the second input parameter:
on run {}
set s to "0"
set b to (random number from 0 to 6) as string
set s to s & b
log s
end run
But in fact you don’t need an explicit coercion here, because it would happen implicitly anyway during the concatenation:
on run {}
set s to "0"
set b to (random number from 0 to 6) -- Integer result.
set s to s & b -- Integer coerced to text for concatenation to the text "0"
log s
end run
1 Like