简体   繁体   中英

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. 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

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 . Your code probably executes in a CultureInfo that has ',' as decimal separator, but your values use '.'. I would advice you to use Double.TryParse using a CultureInfo that has '.' 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, CultureInfo.InvariantCulture)

Specifying CulturInfo.InvariantCulture specifies a culture that expect floating points written as 1.234 (note the period). The source of your problem may be that you time is in the format 1,234 (note the comma). 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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