Double.Tryparse or Convert.Todouble - Which Is Faster and Safer

Double.TryParse or Convert.ToDouble - which is faster and safer?

I did a quick non-scientific test in Release mode. I used two inputs: "2.34523" and "badinput" into both methods and iterated 1,000,000 times.

Valid input:

Double.TryParse = 646ms
Convert.ToDouble = 662 ms

Not much different, as expected. For all intents and purposes, for valid input, these are the same.

Invalid input:

Double.TryParse = 612ms
Convert.ToDouble = ..

Well.. it was running for a long time. I reran the entire thing using 1,000 iterations and Convert.ToDouble with bad input took 8.3 seconds. Averaging it out, it would take over 2 hours. I don't care how basic the test is, in the invalid input case, Convert.ToDouble's exception raising will ruin your performance.

So, here's another vote for TryParse with some numbers to back it up.

Faster alternative to Convert.ToDouble(string)

You can save about 10% by calling Double.TryParse with specific cached instances of NumberStyles and IFormatProvider (i.e. CultureInfo):

var style = System.Globalization.NumberStyles.AllowDecimalPoint;
var culture = System.Globalization.CultureInfo.InvariantCulture;
double.TryParse("1.34515", style, culture, out x);

Both Convert.ToDouble and Double.Parse or Double.TryParse have to assume the input can be in any format. If you know for certain that your input has a specific format, you can write a custom parser that performs much better.

Here's one that converts to decimal. Conversion to double is similar.

static decimal CustomParseDecimal(string input) {
long n = 0;
int decimalPosition = input.Length;
for (int k = 0; k < input.Length; k++) {
char c = input[k];
if (c == '.')
decimalPosition = k + 1;
else
n = (n * 10) + (int)(c - '0');
}
return new decimal((int)n, (int)(n >> 32), 0, false, (byte)(input.Length - decimalPosition));
}

My benchmarks show this to be about 5 times faster than the original for decimal, and up to 12 times if you use ints.

Fastest Way for Converting an Object to Double?

You must be doing a whole whopping lot of these in order to make any sense to spend any time on this. However, I am not here to judge:

So, your code is this:

if (o is IConvertible)
{
d = ((IConvertible)o).ToDouble(null);
}
else
{
d = 0d;
}

I wonder if you would be better off with this

IConvertible convert = o as IConvertible;

if (convert != null)
{
d = convert.ToDouble(null);
}
else
{
d = 0d;
}

Saves you the double cast.

C# double.TryParse with InvariantCulture returns unexpected result

It's not clear from your question what you expected. However, as far as what the code is doing, it's doing exactly what you told it to:

  • Providing NumberStyles.Any tells double.TryParse() to allow any format, except AllowHexSpecifier. This includes the AllowThousands option.
  • Providing the InvariantCulture causes parsing to use the ',' character as the thousands separator.
  • Parsing doesn't actually care where a thousands separator appears. I.e. it doesn't actually force the separator to be in the location where it would indicate a thousands-multiple digit.

So, when you ask it to parse "9,42", that text is interpreted using InvariantCulture (i.e. ignoring your current culture of de-DE), the ',' character is treated as a thousands separator (i.e. ignored for the purpose of computing the actual value), and you get the value 942, just like you asked for.

If you don't want that result, you need to use different arguments for the call to double.TryParse(). You would need to explain what you do want if you want advice on what arguments you should use. All we can say given the information currently in your question is what arguments you apparently don't want.

No overload for method 'TryParse' takes one argument error when using double.TryParse

            double rad = Convert.ToDouble(radius);

if (double.TryParse(rad) == false)

should be

            double rad;
if (!double.TryParse(radius, out rad))

Use ! (not) instead of == false just as better coding practice.

Also, TryParse needs an out value (It does the parsing, no need for Convert.ToDouble and ... your Convert.ToDouble will error if it's not parseable - bad!)

How to load data into program as double? (not string) in c# (window form application - visual studio)

Change these lines in your code to double.

string[] row = new string[values.Length];

for (int j = 0; j < values.Length; j++)
{
row[j] = values[j];
}

Instead

double[] row = new double[values.Length];

for (int j = 0; j < values.Length; j++)
{
row[j] = Convert.ToDouble(values[j]);
}


Related Topics



Leave a reply



Submit