lost9123193
lost9123193

Reputation: 11030

Generate a Random Decimal within a range in Ruby/Rails or Faker

Is there a way on Faker to generate a random decimal between 0-1? https://github.com/faker-ruby/faker/issues/1834

Faker::Number.decimal(l_digits= 2, r_digits= 2).within(range: 0..1) 

The above does not work. Error:

 undefined method `within' for "12.4" String  

12.4 being the random number that's generated

If I can't use faker, is there a way in Ruby to generate this? I just need to generate a number with 2 decimal places between 0 and 1

Upvotes: 6

Views: 5732

Answers (2)

Marian13
Marian13

Reputation: 9238

You can try the following:

Faker::Number.between(from: 0.0, to: 1.0).round(2)

Source:

Upvotes: 8

Pascal
Pascal

Reputation: 8637

Try:

rand.round(2)

rand generates a random number, round rounds it to the desired number of decimals. This might generate a number that has LESS than two decimal digits (e.g. 0.5). If you want to enforce this you can format the random number to a String:

Kernel.format("%.2f", rand)

Where %f is the formating as float and %.2f is specific for two decimal digits. You can actually ommit Kernel and just call format or use % like so:

"%.2f" % rand

(i prefer Kernel.format, seems more reeadable to me)

Now this poses another problem:

pattern = "%.2f"
Kernel.format(pattern, 0) # => "0.00"
Kernel.format(pattern, 0.9999999) # => "1.00"

because it gets rounded up when formatting the number is suddenly not smaller than 1. If by between you meant NOT INCLUDING 1 you will need to tweak it some more:

Kernel.format(pattern, 0.floor(2)) # => "0.00"
Kernel.format(pattern, 0.9999999.floor(2)) # => "0.99"

Upvotes: 1

Related Questions