- Home /
Round to 0.5, 1.5, 2.5 ...
Is there a way to round a number in increments of one but to be offset by one? So for example if a number is 0.7 it would round down to 0.5 and if a number is 1.2 it will round up 1.5. Would it use Mathf.Round or is this impossible? Thanks
Answer by chillersanim · May 24, 2014 at 08:47 PM
Use:
float roundedValue = ((int)input) + 0.5f;
That should do it.
Edit:
If you want to use negative numbers, then use this instead:
float output = Mathf.Sign(input) * (Mathf.Abs((int)input) + 0.5f);
Greetings
Chillersanim
hmmm... after some testing this shows some weird results... I can't seem to figure out why.
void OnDrawGizmos() { Vector3 p = camera.ScreenToWorldPoint(Input.mousePosition); p = new Vector3(((int)p.x) + 0.5f, ((int)p.y) + 0.5f, 0); Gizmos.DrawCube(p, Vector3.one); }
Be aware, that the method "camera.ScreenToWorldPoint" does not fire a ray, but ins$$anonymous$$d it returns a point at the overloaded z distance.
When you want to get where the mouse points on, then you should use the ray class.
$$anonymous$$ore informations can be found in this answer:
http://answers.unity3d.com/questions/265108/shoot-ray-from-mouse-cursor.html
Greetings
Chillersanim
I added a formula for negative numbers.
When you need to work in worldspace, then it is likely that you get negative numbers, so try using the second formula ins$$anonymous$$d.
Greetings
Chillersanim
The only problem is I don't have any colliders set up, so the raycasting won't work for my specific setup. But I guess I will have to change that. Thanks for your help!
Your answer
![](https://koobas.hobune.stream/wayback/20220613145816im_/https://answers.unity.com/themes/thub/images/avi.jpg)