【问题标题】:how to convert string to int c# [closed]如何将字符串转换为 int c# [关闭]
【发布时间】:2016-08-11 14:35:21
【问题描述】:

我想将字符串 (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();
            } 
        }
    }
}

但是,它给了我一个错误:

输入字符串的格式不正确。

我需要进行哪些更改才能使代码正确地将string 转换为int

【问题讨论】:

  • 转换前w.main.temp的内容是什么?
  • 检查w.main.temp的值。很有可能它的格式确实不正确。特别注意逗号和小数点。
  • 当我写 w.main.temp.GetType() 它写 System.String
  • @user3488862 我们知道它的类型,它的价值是什么。 Console.WriteLine(w.main.temp);
  • 304.15 但它是一个字符串,我需要将其转换为 int 因为它在开尔文中并且我需要它以度...

标签: c# string int type-conversion


【解决方案1】:

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

int res = 0;
bool parseSuccessful = int.TryParse(w.main.temp, out res);

//int.TryParse() returns a bool value to indicate whether parsing is Successful  or not.

如果要解析一个数字留给.

例如

 w.main.temp = "123.45";

并且您希望输出 int123。然后使用下面的代码

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

【讨论】:

  • 如果您要使用int.TryParse,您应该捕获返回值以了解它是否失败,或者将其放入if 语句中。它还可以处理null 字符串(将返回false)。最后,如果字符串实际上不是有效的整数值,int.TryParse 将不会更好地工作。
  • 返回false...如何转换成功?
  • @user3488862 false 表示您的字符串不是有效的整数值。听起来你实际上有一个十进制值,所以你要么需要截断以小数开头的字符串,要么先转换为处理小数的类型,然后再转换为int
【解决方案2】:

看起来您的 var 不是整数,您可以先将其四舍五入为 int,也可以只使用 double 而不是 int。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

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

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

      根据您想要的结果,您有多种选择。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-02
        • 1970-01-01
        • 2019-07-16
        • 2013-11-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多