How to

round numbers

Published: 27. October 2011 | Updated: 27. October 2011
License: Microsoft Public License (MS-PL)
Categories: Framework » Math
Tags: C# Math
Was this snippet helpful for you? YESYES / NONO
decimal number = 1234.565m;

// rounds to 2 decimals
Console.WriteLine("Math.Round: {0}", Math.Round(number, 2));
Console.WriteLine("Math.Round ToEven: {0}", Math.Round(number, 2, MidpointRounding.ToEven));
Console.WriteLine("Math.Round AwayFromZero: {0}", Math.Round(number, 2, MidpointRounding.AwayFromZero));

Console.WriteLine("Math.Floor: {0}", Math.Floor(number)); // rounds toward negative infinity
Console.WriteLine("Math.Ceiling: {0}", Math.Ceiling(number)); // rounds toward positive infinity
Console.WriteLine("Math.Truncate: {0}", Math.Truncate(number)); // returns integral part of number
Console Output:
Math.Round: 1234.56
Math.Round ToEven: 1234.56
Math.Round AwayFromZero: 1234.57
Math.Floor: 1234
Math.Ceiling: 1235
Math.Truncate: 1234
Send us feedback about this snippet »



Related Snippets: