简体   繁体   English

输入字符串的格式不正确。 在改变文化的IE中调用TimeSpan.FromSeconds(Convert.ToDouble(time))

[英]Input string was not in a correct format. calling TimeSpan.FromSeconds(Convert.ToDouble(time)) in IE on Changing Culture

Hi im using given below method to convert in to string its working fine chrome but in IE its through exception Input string was not in a correct format. 嗨我使用给定的下面的方法转换为字符串其工作精细铬,但在IE中它通过异常输入字符串不是正确的格式。 at this line 在这条线上

 s = TimeSpan.FromSeconds(Convert.ToDouble(time));

these are values im passing to it 这些是我传递给它的价值观

600, 298.8, 65505, 69, 70, 20.5, 20.5, 20.5, 20.5, 1840.4, 682, 1040.3

in chrome its working but in IE it gives exception on second value when i change the culture to french language please help me out what is the problem 在Chrome中它的工作,但在IE中,当我将文化改为法语时,它会给出第二个值的例外,请帮助我解决问题

public static String ConvertTimeToString(this string time)   
{

    if (String.IsNullOrEmpty(time))
    {
        return time;
    }

    TimeSpan s;

    if (time.IndexOf(':') >= 0)
    {
        s = TimeSpan.Parse(time);
    }
    else
    {
        s = TimeSpan.FromSeconds(Convert.ToDouble(time));
    }

    return s.ConvertTimeToString();
}    

The failure is probably in the call Convert.ToDouble . 失败可能是在调用Convert.ToDouble Your code probably executes in a CultureInfo that has ',' as decimal separator, but your values use '.'. 您的代码可能在CultureInfo中执行,其中包含','作为小数分隔符,但您的值使用'。'。 I would advice you to use Double.TryParse using a CultureInfo that has '.' 我建议你使用具有'。'的CultureInfo来使用Double.TryParse as decimal separator instead: 作为小数分隔符:

Double value;
if (Double.TryParse(time, NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), out value))
{
    s = TimeSpan.FromSeconds(value);
}

You need to specify an IFormatProvider when you use Convert.ToDouble(time) : 使用Convert.ToDouble(time)时需要指定IFormatProvider

Convert.ToDouble(time, CultureInfo.InvariantCulture)

Specifying CulturInfo.InvariantCulture specifies a culture that expect floating points written as 1.234 (note the period). 指定CulturInfo.InvariantCulture指定一种文化,期望浮点写为1.234 (注意句点)。 The source of your problem may be that you time is in the format 1,234 (note the comma). 问题的根源可能是您的time格式为1,234 (请注意逗号)。 Or maybe it is the reverse: You don't specify an IFormatProvider and the current culture of you ASP.NET process uses comma as a decimal separator, but the string provided uses period? 或者它可能是相反的:您没有指定IFormatProvider和您当前的文化ASP.NET进程使用逗号作为小数分隔符,但提供的字符串使用句点?

If the decimal point used isn't consistent you should either fix it at the source (not sure what the source is here) or as a last resort you can replace comma by period: 如果使用的小数点不一致,您应该在源处修复它(不确定源是什么)或作为最后的手段,您可以按句点替换逗号:

Convert.ToDouble(time.Replace(",", ".") , CultureInfo.InvariantCulture)

However, trying to parse a string and not knowing the what to expect is not the best thing to do. 但是,尝试解析字符串而不知道要发生什么并不是最好的事情。

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

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