I just wonder how to do a code which round of to a number off two decimals.
For example if I have the code text(54.98*1.52), the answer will be 83.5696. What should I do if I want it to print 83.57 instead of 83.5697?
If the only reason you want to round the number is for display purposes (print, text etc) then use
string.format("%.2f", 3.5694) --returns 3.57 (Edit: wrote text.format by mistake)
If you google printf codes you’ll see an explanation of the format code. %f is the code for a floating point number, and .2 means 2 decimal places.
If however you need the number to be rounded for the purpose of further computation, you can use something like this, to avoid converting the number to a string:
function math.round(number, places) --use -ve places to round to tens, hundreds etc local mult = 10^(places or 0) return math.floor(number * mult + 0.5) / mult end
Note also that
text string format can accept multiple arguments. I use it for doing arcade game scorelines, eg if you want the score to always display as 6 digits (regardless of how low it is, eg “000015”) in classic arcade style. You can do something like this:
string.format("Frames Per Second %.2f Lives %d Score %.6d", FPS, playerHealth, score) where the 3 arguments following the string correspond to each of the print codes.
OK! But how would you do if the code is:
text(54.98*1.52,500,500) if you want it to be writing 83.57 in the position (500,500)
Here’s 3 ways of using string.format.
supportedOrientations(LANDSCAPE_ANY) function setup() end function draw() background(40, 40, 50) fill(255) text(string.format("Result = %.2f",54.98*1.52),500,500) val=54.98*1.52 text(string.format("Result = %.2f",val),500,450) str=string.format("Result = %.2f",val) text(str,500,400) end
Ok! Thank you everybody!
whats the difference between %d and %.6d?
try it and see