简体   繁体   English

从double转换为decimal

[英]Convert from double to decimal

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. 我正在使用Google天气XML文件在C#中开发天气应用程序,我在类文件中使用计算时遇到问题。 I am trying to convert farenheit to celcius with the folliowing method: 我试图用下面的方法将farenheit转换为celcius:

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 错误23:'Weather.Helper.CalculateTemp(decimal)'的最佳重载方法匹配有一些无效的参数

Error 24: Argument 1: cannot convert from 'double' to 'decimal' 错误24:参数1:无法从'double'转换为'decimal'

Error 25 : Operator '/' cannot be applied to operands of type 'decimal' and 'double' 错误25:运算符'/'不能应用于'decimal'和'double'类型的操作数

I am not sure how to fix this.. 我不知道如何解决这个问题..

Don't use decimal for a temperature, double is enough. 不要使用decimal表示温度, double就足够了。

Also, don't return "°C" cause it's a number, not a string: 另外,不要返回"°C"因为它是一个数字,而不是一个字符串:

public static double CalculateTemp(double input)
{
    return Math.Round((input - 32) * 5 / 9);
}

1.0 is a double , not a decimal . 1.0double decimal ,而不是decimal Use the suffix m or M to mark a number as a decimal . 使用后缀mM将数字标记为decimal
("M" stands for "Money", as this type is normally used for financial transactions.) (“M”代表“Money”,因为此类型通常用于金融交易。)

(input - 32) * 5M / 9M

and you won't even need the * 1.0 你甚至不需要* 1.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. 另请注意,由于末尾的"°C" ,您必须更改方法签名以返回字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM