如何将字符串转换为int c#

如何将字符串转换为int c#,c#,string,int,type-conversion,C#,String,Int,Type Conversion,我想将字符串(w.main.temp)转换为整数。我正在使用以下代码: using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Collections;

我想将字符串(
w.main.temp
)转换为整数。我正在使用以下代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Collections;

namespace project1
{

    interface IWeatherDataService
{
       // public WeatherData GetWeatherData(Location location);

}

    public class WeatherData
    {
        public string temp { get; set; }
    }
    public class Location
    {
        public string name { get; set; }
        public string id { get; set; }

        public WeatherData main { get; set; }

    }
    public class WeatherDataServiceException
    {

    }

    class Program
    {
        static void Main(string[] args)
        {
           RunAsync().Wait();
        }
        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5/weather");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                string City = "ho chi minh";
                string Key = "ca618d97e8b322c883af330b7f103f2d";

                HttpResponseMessage response = await client.GetAsync("?q=" + City + "&APPID="+Key);
                if(response.StatusCode == HttpStatusCode.OK)
                {

                    Location w = response.Content.ReadAsAsync<Location>().Result;

                    int res = Convert.ToInt32(w.main.temp);

                    //Console.WriteLine(w.main.temp.GetType());

                    Console.WriteLine("id city: " + w.id);
                    Console.WriteLine("city: " + w.name);
                     Console.WriteLine("temperature: " + w.main.temp);
                }
                Console.ReadKey();
            } 
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
Net系统;
使用System.Net.Http;
使用System.Net.Http.Header;
使用系统文本;
使用System.Threading.Tasks;
使用系统集合;
命名空间项目1
{
接口IWeatherDataService
{
//公共天气数据获取天气数据(位置);
}
公共类天气数据
{
公共字符串temp{get;set;}
}
公共类位置
{
公共字符串名称{get;set;}
公共字符串id{get;set;}
公共天气数据主{get;set;}
}
公共类WeatherDataServiceException
{
}
班级计划
{
静态void Main(字符串[]参数)
{
RunAsync().Wait();
}
静态异步任务RunAsync()
{
使用(var client=new HttpClient())
{
client.BaseAddress=新Uri(“http://api.openweathermap.org/data/2.5/weather");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(新的MediaTypeWithQualityHeaderValue(“应用程序/json”);
字符串城市=“胡志明”;
字符串键=“ca618d97e8b322c883af330b7f103f2d”;
HttpResponseMessage response=wait client.GetAsync(“?q=“+City+”&APPID=“+Key”);
if(response.StatusCode==HttpStatusCode.OK)
{
位置w=response.Content.ReadAsAsync().Result;
int res=转换为NT32(带主温度);
//Console.WriteLine(w.main.temp.GetType());
控制台写入线(“id城市:+w.id”);
Console.WriteLine(“城市:+w.name”);
控制台写入线(“温度:+w主温度”);
}
Console.ReadKey();
} 
}
}
}
但是,它给了我一个错误:

输入字符串的格式不正确


要使代码正确地将
string
转换为
int
,我需要更改什么?

只需使用
int.TryParse(string,out int参数)

如果您想解析一个遗留到

e、 g

您希望输出
int
123
。然后使用以下代码

if (w.main.temp.IndexOf(".") >= 0)
{
    parseSuccessful = int.TryParse(w.main.temp.Substring(0, w.main.temp.IndexOf(".")), out res);
}

我检查了您请求的服务的响应

w.main.temp的值中有“.”(例如:285.61,我猜它返回的值为开尔文)。所以它不是整数

根据您想要的结果,您有几个选项

  • 你可以得到“.”的左边
  • 您可以先将其转换为十进制,然后获取其下限值或上限值,然后将其转换为int
  • 等等

  • 显然,如果字符串不是整数,就不能将其转换为整数,因为它不知道如何剪切。
    我的号码是304.15,所以你必须把它转换成双倍

    看起来您的var不是整数,您可以先将其四舍五入为整数,也可以使用双精度代替整数。

    在转换之前,
    w.main.temp
    的内容是什么?检查
    w.main.temp
    的值。很有可能它的格式确实不正确。特别注意逗号和小数点。当我写w.main.temp.GetType()时,它会写系统。String@user3488862我们知道它的类型,它的价值是什么<代码>控制台写入线(带主温度)304.15,但它是一个字符串,我需要将它转换为int,因为它是开尔文,我需要以度为单位…如果要使用
    int.TryParse
    您应该捕获返回值以了解它是否失败,或者将其放入
    If
    语句中。它还可以处理
    null
    字符串(将返回
    false
    )。最后,如果字符串实际上不是有效的整数值,则
    int.TryParse
    的效果不会更好。它返回false。。。如何成功转换?@user3488862 false表示字符串不是有效的整数值。听起来您实际上得到了一个十进制值,因此您需要截断以十进制开头的字符串,或者首先转换为处理小数的类型,然后转换为
    int
     w.main.temp = "123.45";
    
    if (w.main.temp.IndexOf(".") >= 0)
    {
        parseSuccessful = int.TryParse(w.main.temp.Substring(0, w.main.temp.IndexOf(".")), out res);
    }