How do I round a floating-point value?
Category: System, viewed: 2K time(s).
To round floating-point value to a whole number we can use the Math.Round() methods. The example below showing you how to round to the nearest whole number and to round the value to a specific number of fraction digits.
using System;
namespace Kodecsharp.Example.System
{
public class NumberRounding
{
public static void Main(string[] args)
{
int number = (int) Math.Round(100.55555); // number = 101
Console.Out.WriteLine("Number " + number);
//
// Round the number to the number with two fraction digits
//
double result = Math.Round(100.55555, 2);
Console.Out.WriteLine("Number " + result); // result = 100.56
//
// If the number being rounded is half way between two numbers,
// the Round method will always round tho the nearest even number
// as in the following example.
//
decimal val1 = (decimal) Math.Round(5.5); // val1 = 6
decimal val2 = (decimal) Math.Round(6.5); // val2 = 6
Console.Out.WriteLine("Val1 = " + val1);
Console.Out.WriteLine("Val2 = " + val2);
Console.ReadLine();
}
}
}