Random number between two decimal places in Swift

I would like to get a random number between two small decimal numbers.

Between can be 0.8 and 1.3.

var duration = CGFloat(arc4random() % 0.8) / 1.3 

or

 var duration = CGFloat(arc4random() % 0.5) + 0.8 

Thanks!

+6
source share
1 answer

Here is a general function that I just wrote quickly to get a random number within a range.

 func randomBetweenNumbers(firstNum: CGFloat, secondNum: CGFloat) -> CGFloat{ return CGFloat(arc4random()) / CGFloat(UINT32_MAX) * abs(firstNum - secondNum) + min(firstNum, secondNum) } 

It takes a random number, finds the remainder of this number divided by the difference between the two parameters, and then adds a smaller number. This ensures that a random number must be between two numbers.

Disclaimer: I have not tested this yet.

EDIT : Now this function does what you want.

+33
source

Source: https://habr.com/ru/post/975807/


All Articles