2

I am developing a weather application in C# using the Google weather XML file and I am having trouble using calculations in a class file. I am trying to convert farenheit to celcius with the folliowing method:

public static class Helper
{
    public static decimal CalculateTemp(decimal input)
    {
     return Math.Round((input - 32) * 5 / 9 / 1.0) * 1.0 + "°C";
    }
}

"input" is where the weather data is called such as the highest temp. of today. I am getting the following errors upon compiling:

Error 23: The best overloaded method match for 'Weather.Helper.CalculateTemp(decimal)' has some invalid arguments

Error 24: Argument 1: cannot convert from 'double' to 'decimal'

Error 25 : Operator '/' cannot be applied to operands of type 'decimal' and 'double'

I am not sure how to fix this..

Community
  • 1
  • 1
Rhys Towey
  • 2,355
  • 1
  • 24
  • 35
  • 3
    Write sane code, don't divide by 1, don't multiply by 1, don't append strings to floating point numbers and the compiler will go "ah, so that's what you actually meant". – Hans Passant Mar 07 '12 at 12:38

3 Answers3

6

Don't use decimal for a temperature, double is enough.

Also, don't return "°C" cause it's a number, not a string:

public static double CalculateTemp(double input)
{
    return Math.Round((input - 32) * 5 / 9);
}
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • 1
    So true. And since he's rounding off to whole numbers, he doesn't even need floating point at all. But his question was where did the error come from, and the error messages suggest that this example is a much simplified case of his actual program, so maybe he really does need a `decimal`. – Mr Lister Mar 07 '12 at 12:37
5

1.0 is a double, not a decimal. Use the suffix m or M to mark a number as a decimal.
("M" stands for "Money", as this type is normally used for financial transactions.)

(input - 32) * 5M / 9M

and you won't even need the * 1.0

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
0

if you want to use the decimal (rather than double), you'd have to refactor as:

public static class Helper
{
    public static string CalculateTemp(decimal input)
    {
        return Math.Round(((input - 32) * 5 / 9 / 1.0m)) + "°C";
    }
}

or:

public static class Helper
{
    public static string CalculateTemp(decimal input)
    {
        return Math.Round(((input - 32) * 5 / 9 / (decimal)1.0)) + "°C";
    }
}

notice also that you have to change the method signature to return a string due to the "°C" at the end.

jim tollan
  • 22,305
  • 4
  • 49
  • 63