Home > Net >  Check if float contains decimal with 0
Check if float contains decimal with 0

Time:08-24

I am generating a random floating value between 1.00 and 5.00. Sometimes the value comes as 1.08 or 3.09. I do not wish to have this, instead it should be 1.00 or 3.00 when it comes to such a case. That is whenever there is a decimal with 0 soon after, the value should always be .00.

Such that if X.0Y is a value, the final value should be X.00.

Example: value = 3.08; output final value = 3.00

public float selectedValueRange;

void Start(){
  selectedValueRange = Random.Range (1.0, 5.0  1.0f);
  selectedValueRange = Mathf.Round (selectedValueRange * 100.0f) * 0.01f;
}

CodePudding user response:

You can get rid of everything after the decimal point and then check if the difference between the new value and the previous number is less than 0.1f which means your number is in this format x.0y. If it is then reassign the new value as the random value. Something like the following code:

int number = (int)selectedValueRange;
if(selectedValueRange-number < 0.1f){
   selectedValueRange = (float)number;
}
  • Related