I have a method that returns the perimeter of a triangle. One of the parameters to this method is the precision.
When I call my function specifying the precision I don't get the results I expect. I don't know how I can resolve the problem with Math.Round
.
public static double TrianglePerimeter(int a, int b, int c, int precision = 2)
{
if (a < 0 || b < 0 || c < 0 || precision < 2 || precision > 8)
throw new ArgumentException("wrong arguments");
if (a + b < c || a + c < b || b + c < a)
throw new ArgumentException("object not exist");
return Math.Round((double)a+(double)b+(double)c, precision);
}
Example:
a = 1, b = 2, c = 3, precision = 3
a = 1, b = 1, c = 1, precision = 5
As others have pointed out, decimal rounding won't get you what you need because 12 = 12.0 = 12.000. The Round function will only work for you if you actually have significant digits that extend to those decimal places (e.g. 12.0011 would round to 12.001 if you did Math.Round(12.0011, 3);
What you need to do is format the return value as a string with the proper format. Notice the return result is string, not double. Something like this:
public static string TrianglePerimeterS(int a, int b, int c, int precision = 2)
{
if (a < 0 || b < 0 || c < 0 || precision < 2 || precision > 8)
throw new ArgumentException("wrong arguments");
if (a + b < c || a + c < b || b + c < a)
throw new ArgumentException("object not exist");
// Build the format string in the format of "0.000" if precision is 3
string formatString = "0." + new string('0', precision);
double value = Math.Round((double)a + (double)b + (double)c, precision);
string result = value.ToString(formatString);
return result;
}