[Closed] Limit fractional digits?
Hi,
Is there a way to control the fractional digits of a randomly generated float number?
I dont want random 1 100 to return 87,3283 but to return 87,33 for example
(
fn limit x n =
(
(floor (x * 10 ^ n + 0.5)) / 10 ^ n
)
local x = random 1. 100.
format "% => %
" x (limit x 2)
)
EDIT: edited the function a bit to avoid conversion to integer and back
Thank you very much!
Seems that I’m a bit slow…could you explain (maybe pseudocode?) What exactly that function requres and processes? I of course may only copypasta it but I want to understand it…and as I said I feel I’m a bit slow at getting this code ^^
the main part is the function definition of ‘limit’
the rest is just an example of use.
limit expects 2 input parameters:
x – the number we want to limit
n – the number of digits on the right of the decimal point that we want.
I have edited the function a bit so that it will be easier to understand and so that it will be a bit more efficient.
the function do the following steps in one math expression:
- multiply ‘x’ by 10 in the power of n so that all the wanted digits will be on the left of the decimal point .
- add 0.5 to round off the smallest digit. (if you want to chop, remove this part)
- delete all digits on the right of the decimal point using the ‘floor’ function.
- divide by 10 in the power of n to return the number to it’s original size.
Hope this explains it.
I didn’t give any thought to negative numbers, I admit but it looks like it’s working ok to them. Can you give an example?
I get these results for example and I think they look ok:
-89.8469 => -89.85
-48.2213 => -48.22