We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hey! I've started using p5.js after using processing, and so I am stuck trying to change a float into an int.
I want to get a random integer so I can upload a random image:
// get a random number for image
var imgNum;
function setup(){
imgNum = random(0, 14);
}
How would I go about converting the random number into an int?
thanks!
Answers
Use unary operator
~2x:imgNum = ~~random(14);. :ar!There are some other approaches too. ;;)
For example the
|operator:imgNum = random(14) | 0;orimgNum = 0 | random(14);.The article below is about transitioning Processing's Java Mode to p5.js: :bz
https://GitHub.com/processing/p5.js/wiki/Processing-transition
@beccarose -- change a float into an int with
int()-- use this if you want your code to be simple and clear. See the p5.js int reference page:Using
--or| 0is indeed very " :ar! "They are not intended for this purpose -- but they are efficient ways to force the answer to be an int as a side-effect of doing something different (integer subtraction bitwise not, or a logical "or" test).
It's not the decrement operator
--, but 2 Bitwise NOT tildes:~~: :-\"https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT
BtW, we can replace
| 0w/& -1too:imgNum = random(14) & -1;Also
imgNum = random(14) >> 0;,imgNum = random(14) >>> 0;,imgNum = random(14) << 0;, etc. :PAnd other more conservative options below if you prefer: :-B
@jeremydouglass would you be able to provide a specific example. I have converted types in other languages, but p5.js only uses var, so not sure how using int() would work in that case?
@GoToLoop thanks I'll give those a go tonight
@GoToLoop just tried the "pirate" way 2x tildes and worked really well. thank you!
(note in Bristol my home town we are really into pirates...oooh-argh!)
Although variables in the JS language don't have types, the data they store DO! L-)
And it's misinformation that
varis the only way to declare variables in JS. Actually there are 5: @-)var: https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/varlet: https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/letconst: https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/constfunction: https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/functionclass: https://developer.Mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/classI bet you're finding strange that
function&classare also variable declarations. >-)But when not using their anonymous expression form, rather their declaration form, they do create a variable! ;;)
@beccarose -- the forum formatting may have hidden the fact that my answer linked to the p5.js int() reference page, which also gives many examples:
@beccarose - in which case you must know of Pirate Pete :ar! :D :ar!