-
Notifications
You must be signed in to change notification settings - Fork 164
/
RoundNumberPerformance.cs
54 lines (48 loc) · 1.89 KB
/
RoundNumberPerformance.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using static System.Console;
using static System.Math;
using System.Diagnostics;
public class Program {
public static void Main() {
var tempo = new Stopwatch();
WriteLine("Decimal");
tempo.Start();
for (var valor = -10000M; valor <= 10000M; valor += 0.05M) valor.RoundMidPoint();
tempo.Stop();
WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
WriteLine("Double");
tempo.Start();
for (var valor = -10000.0; valor <= 10000.0; valor += 0.05) valor.RoundMidPoint();
tempo.Stop();
WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
WriteLine("Decimal Alternativo");
tempo.Start();
for (var valor = -10000M; valor <= 10000M; valor += 0.05M) valor.RoundMidPointAlt();
tempo.Stop();
WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
WriteLine("Double Alternativo");
tempo.Start();
for (var valor = -10000.0; valor <= 10000.0; valor += 0.05) valor.RoundMidPointAlt();
tempo.Stop();
WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
}
}
public static class RoundUtil {
public static Decimal RoundMidPoint(this Decimal value) => Sign(value) * Ceiling(Abs(value) * 2) / 2;
public static double RoundMidPoint(this double value) => Sign(value) * Ceiling(Abs(value) * 2) / 2;
public static Decimal RoundMidPointAlt(this Decimal value) {
int intPart = (int)value;
decimal decimalPart = value - intPart;
if (0 < decimalPart && decimalPart <= 0.5M) return intPart + 0.5M;
else if (0.5M < decimalPart) return intPart + 1;
else return intPart;
}
public static double RoundMidPointAlt(this double value) {
int intPart = (int)value;
double decimalPart = value - intPart;
if (0 < decimalPart && decimalPart <= 0.5) return intPart + 0.5;
else if (0.5 < decimalPart) return intPart + 1;
else return intPart;
}
}
//http://pt.stackoverflow.com/q/16185/101