Math

Using System

using System;
class Program
{
public static void Main()
{
double value = 1.234;
Console.WriteLine(*"ROUND: {0}"*, **Math.Round**(value));
}
}ROUND: 1

Overload

Double

Decimal

Enum

using System;
class Program
{
static void Main()
{
*//
// Round double type in three ways.
//*
double before1 = *123.45*;
double after1 = **Math.Round**(before1, 1,
MidpointRounding.AwayFromZero); *// Rounds "up"*
double after2 = **Math.Round**(before1, 1,
MidpointRounding.ToEven); *// Rounds to even*
double after3 = **Math.Round**(before1);
Console.WriteLine(before1); *// Original*
Console.WriteLine(after1);
Console.WriteLine(after2);
Console.WriteLine(after3);
*//
// Round decimal type.
//*
decimal before2 = *125.101M*;
decimal after4 = **Math.Round**(before2);
decimal after5 = **Math.Round**(before2, 1);
Console.WriteLine(before2); *// Original*
Console.WriteLine(after4);
Console.WriteLine(after5);
}
}123.45
123.5 <-- MidpointRounding.AwayFromZero
123.4 <-- MidpointRounding.ToEven
123
125.101
125
125.1

using System;
class Program
{
static void Main()
{
for (double i = 0.1; i < 0.99; i += 0.1)
{
Console.WriteLine(*"{0}=({1},{2})"*, i,
Math.Round(i, **MidpointRounding.ToEven**),
Math.Round(i, **MidpointRounding.AwayFromZero**));
}
}
}0.1=(0,0)
0.2=(0,0)
0.3=(0,0)
0.4=(0,0)
0.5=(0,1)
0.6=(1,1)
0.7=(1,1)
0.8=(1,1)
0.9=(1,1)

using System;
using System.Diagnostics;
class Program
{
const int _max = 100000000;
static void Main()
{
*// Version 1: use Math.Round with argument of 0.*
var s1 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
double d = **Math.Round**(1.3665, 0);
if (d == 1.5)
{
throw new Exception();
}
}
s1.Stop();
*// Version 2: use Math.Round with argument of 1.*
var s2 = Stopwatch.StartNew();
for (int i = 0; i < _max; i++)
{
double d = **Math.Round**(1.3665, 1);
if (d == 1.5)
{
throw new Exception();
}
}
s2.Stop();
Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(*"0.00 ns"*));
Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) / _max).ToString(*"0.00 ns"*));
}
}*5.52 ns* Math.Round, 0
*4.91 ns* Math.Round, 1

If

© 2007-2022 sam allen.

see site info on the changelog.