fork download
  1. using System;
  2. using static System.Console;
  3. using static System.Math;
  4. using System.Diagnostics;
  5.  
  6. public class Program {
  7. public static void Main() {
  8. var tempo = new Stopwatch();
  9. WriteLine("Decimal");
  10. tempo.Start();
  11. for (var valor = -10000M; valor <= 10000M; valor += 0.05M) valor.RoundMidPoint();
  12. tempo.Stop();
  13. WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
  14. WriteLine("Double");
  15. tempo.Start();
  16. for (var valor = -10000.0; valor <= 10000.0; valor += 0.05) valor.RoundMidPoint();
  17. tempo.Stop();
  18. WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
  19. WriteLine("Decimal Alternativo");
  20. tempo.Start();
  21. for (var valor = -10000M; valor <= 10000M; valor += 0.05M) valor.RoundMidPointAlt();
  22. tempo.Stop();
  23. WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
  24. WriteLine("Double Alternativo");
  25. tempo.Start();
  26. for (var valor = -10000.0; valor <= 10000.0; valor += 0.05) valor.RoundMidPointAlt();
  27. tempo.Stop();
  28. WriteLine("Arredondando em ms: {0}", tempo.ElapsedMilliseconds);
  29. }
  30. }
  31.  
  32. public static class RoundUtil {
  33. public static Decimal RoundMidPoint(this Decimal value) => Sign(value) * Ceiling(Abs(value) * 2) / 2;
  34.  
  35. public static double RoundMidPoint(this double value) => Sign(value) * Ceiling(Abs(value) * 2) / 2;
  36.  
  37. public static Decimal RoundMidPointAlt(this Decimal value) {
  38. int intPart = (int)value;
  39. decimal decimalPart = value - intPart;
  40. if (0 < decimalPart && decimalPart <= 0.5M) return intPart + 0.5M;
  41. else if (0.5M < decimalPart) return intPart + 1;
  42. else return intPart;
  43. }
  44.  
  45. public static double RoundMidPointAlt(this double value) {
  46. int intPart = (int)value;
  47. double decimalPart = value - intPart;
  48. if (0 < decimalPart && decimalPart <= 0.5) return intPart + 0.5;
  49. else if (0.5 < decimalPart) return intPart + 1;
  50. else return intPart;
  51. }
  52. }
  53.  
  54. //http://pt.stackoverflow.com/q/16185/101
Success #stdin #stdout 0.18s 17348KB
stdin
Standard input is empty
stdout
Decimal
Arredondando em ms: 83
Double
Arredondando em ms: 86
Decimal Alternativo
Arredondando em ms: 158
Double Alternativo
Arredondando em ms: 160