This C# program demonstrates how to round numbers in C#. The first part demonstrates rounding to the nearest integer, tenth, and hundredth of a value. The second part demonstrates the two midpoint rounding rules: away from zero and toward the even value.
using System; namespace XoaX { class Program { static void Main(string[] args) { double dA = 937.352; double dB = 3.18547; // Rounding to a particular digit Console.WriteLine("dA = " + dA + " Integer = " + Math.Round(dA) + " Tenth = " + Math.Round(dA, 1) + " Hundredth = " + Math.Round(dA, 2)); Console.WriteLine("dB = " + dB + " Integer = " + Math.Round(dB) + " Tenth = " + Math.Round(dB, 1) + " Hundredth = " + Math.Round(dB, 2)); // Rounding rules at midpoints double dX = 7.5; double dY = 8.5; Console.WriteLine("dX = " + dX + " AwayFromZero = " + Math.Round(dX, MidpointRounding.AwayFromZero) + " ToEven = " + Math.Round(dX, MidpointRounding.ToEven)); Console.WriteLine("dY = " + dY + " AwayFromZero = " + Math.Round(dY, MidpointRounding.AwayFromZero) + " ToEven = " + Math.Round(dY, MidpointRounding.ToEven)); } } }
dA = 937.352 Integer = 937 Tenth = 937.4 Hundredth = 937.35 dB = 3.18547 Integer = 3 Tenth = 3.2 Hundredth = 3.19 dX = 7.5 AwayFromZero = 8 ToEven = 8 dY = 8.5 AwayFromZero = 9 ToEven = 8 Press any key to continue . . .
© 20072024 XoaX.net LLC. All rights reserved.