2

I need to round to the next biggest magnitude. So 6.66 rounds to 7, but -6.66 rounds to -7.

At the moment I'm doing:

int result = Math.Ceil(num);
if(num < 0)
   result -= 1;

I'm in the middle of a 2k*2k*2k nested loop, so saving an if/subtract could really help.

Steve555
  • 173
  • 1
  • 7
  • @leppie, sounds like Mathf used in Unity3D, but OP should definitely be more specific... http://docs.unity3d.com/ScriptReference/Mathf.html – walther Jan 07 '15 at 15:04
  • Oops, sorry is that not standard? (Newish to C# and coding in Unity3D). So substitute whatever the standard C# Ceil() is. – Steve555 Jan 07 '15 at 15:04
  • Nope.. In standard C# there's `Math` http://msdn.microsoft.com/en-us/library/system.math%28v=vs.110%29.aspx – walther Jan 07 '15 at 15:05

1 Answers1

1

Check "Round Away from Zero" in this blog post:

public static int RoundAwayFromZero(decimal value)
{
    return value >= 0 ? (int)Math.Ceiling(value) : (int)Math.Floor(value);
}
BCdotWEB
  • 1,009
  • 1
  • 14
  • 35
  • Where did the other Answer go: (Math.Round(num,MidpointRounding.AwayFromZero)?? – Steve555 Jan 07 '15 at 15:26
  • Thanks, marked it as correct as it's exactly what I requested. Interestingly, on a loop of 125 million iterations: num >= 0 ? (int)Math.Ceiling(num) : (int)Math.Floor(num); //5521 ms Math.Round(num, MidpointRounding.AwayFromZero); // 4007 ms – Steve555 Jan 07 '15 at 15:30
  • MidpointRounding only applies to numbers that are at the Midpoint, that is x.5, which means it doesn't do what you want it to. Also, the suggested solution works, but it's just a fancy if, so you have the same branch. – William Jan 07 '15 at 15:36
  • @William. Thanks, maybe that's why answerer deleted it. – Steve555 Jan 07 '15 at 17:03