Generate random number between 1 and 3 / including 1 decimal place

10,145

You can multiply the result like this:

float result = rnd.Next(10, 31) * .1f;

This will result in a range from 1.0 to 3.0, stepping by .1.

Share:
10,145
user3609198
Author by

user3609198

Updated on June 17, 2022

Comments

  • user3609198
    user3609198 almost 2 years

    I can generate a random number between 1 and 3 fairly easy.

    float x = Random.Range(1, 3);
    

    But I am trying to generate a random number between 1 and 3, including 1 decimal place. i.e 1.0, 1.1, 1.2 - 2.8, 2.9, 3.0 Any help appreciate. I am finding no easy function to do this.

    Note - I am using .cs script in Unity

  • zmbq
    zmbq almost 10 years
    Change it to rnd.Next(10, 31), the upper limit is exclusive, not inclusive.
  • Nathan A
    Nathan A almost 10 years
    Ya, I just released that. Updating.
  • user3609198
    user3609198 almost 10 years
    Sorry I should have noted I am using a script in the Unity program to do this. Getter the error, 'UnityEngine.Random' does not contain a definition for 'Next' and not extension method 'Next' of type 'UnityEngine.Random' could be found.
  • Nathan A
    Nathan A almost 10 years
    Can't say I'm familiar with Unity, but it it's anything like C#, the concept should still work. Use your original method name Random.Range, but update the values and multiply like I mentioned. It should work.
  • user3609198
    user3609198 almost 10 years
    I think its working as its not throwing an error, now have code double result = Random.Range(-41, 41) * .1 Problem is the method Im putting it into 'transform.position', needs a float....The best overloaded method match for 'UnityEngine.Vector3(float,float, float)' has some invalid arguments
  • Nathan A
    Nathan A almost 10 years
    Ok, use a float instead: float result = Random.Range(-41, 41) * .1f
  • user3609198
    user3609198 almost 10 years
    Got it working with this, had to do a little trick to input float but method worked. Thanks