HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMajor

Divide two numbers, then apply a custom rounding rule

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
divideruleapplynumberscustomtwothenrounding

Problem

If the fractional part of the number is greater than 0.6, round up; if less, round down.
I need feedback about my code.

public static double DivisionMethod(double a, double b)
{
      double div = a / b;
      double temp = Math.Floor(div);
      double fractional = div - temp;

      if (fractional > 0.6)
      {
          return Math.Ceiling(div);
      }
      else
      {
          return Math.Floor(div);
      }
}

Solution

DivisionMethod is a pretty vague/poor name for your method; any method with the word "method" in it should raise a "bad name" flag!

Also, hard-coding the threshold into the function takes away flexibility. Perhaps I'd consider an optional parameter, like this:

public static double RoundedDivision(double a, double b, double threshold = 0.6)


Okay, not sure RoundedDivision is a much better name... naming is hard!. This is where XML comments can help:

/// 
/// Divides a by b and round up if quotient is
/// greater than threshold, round down if it's less. 
/// 
public static double RoundedDivision(double a, double b, double threshold = 0.6)


It's probably best to call a cat, a cat: a is the dividend and b is the divisor, so the method would be clearer with a signature like this:

/// 
/// Divides dividend by divisor and round up if quotient is
/// greater than threshold, round down if it's less. 
/// 
public static double RoundedDivision(double dividend, double divisor, double threshold = 0.6)


As was mentioned in the comments, there's an ambiguity issue with the threshold: what happens if the quotient is exactly equal to the threshold?

Code Snippets

public static double RoundedDivision(double a, double b, double threshold = 0.6)
/// <summary>
/// Divides <c>a</c> by <c>b</c> and round up if quotient is
/// greater than <c>threshold</c>, round down if it's less. 
/// </summary>
public static double RoundedDivision(double a, double b, double threshold = 0.6)
/// <summary>
/// Divides <c>dividend</c> by <c>divisor</c> and round up if quotient is
/// greater than <c>threshold</c>, round down if it's less. 
/// </summary>
public static double RoundedDivision(double dividend, double divisor, double threshold = 0.6)

Context

StackExchange Code Review Q#55333, answer score: 20

Revisions (0)

No revisions yet.