相关疑难解决方法(0)

Double.TryParse或Convert.ToDouble - 哪个更快更安全?

我的应用程序使用VSTO读取Excel文件并将读取的数据添加到StringDictionary.它仅添加具有几位数字的数据(1000 1000,2 1000,34 - 逗号是俄罗斯标准中的分隔符).

最好检查当前字符串是否是合适的数字?

object data, string key; // data had read

try
{
  Convert.ToDouble(regionData, CultureInfo.CurrentCulture);
  dic.Add(key, regionData.ToString());
}
catch (InvalidCastException)
{
  // is not a number
}
Run Code Online (Sandbox Code Playgroud)

要么

double d;
string str = data.ToString();
if (Double.TryParse(str, out d)) // if done, then is a number
{
  dic.Add(key, str);
}
Run Code Online (Sandbox Code Playgroud)

我必须使用StringDictionary而不是Dictionary<string, double>因为以下解析算法问题.

我的问题:哪种方式更快?哪个更安全?

打电话Convert.ToDouble(object)或者打电话会更好Convert.ToDouble(string)吗?

.net c# double parsing

79
推荐指数
6
解决办法
11万
查看次数

更快的decimal.Parse替代品

我注意到decimal.Parse(number, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture)比基于Jeffrey Sax的代码的自定义十进制解析方法慢大约100%,该代码来自Faster替代Convert.ToDouble

public static decimal ParseDecimal(string input) {
    bool negative = false;
    long n = 0;

    int len = input.Length;
    int decimalPosition = len;

    if (len != 0) {
        int start = 0;
        if (input[0] == '-') {
            negative = true;
            start = 1;
        }

        for (int k = start; k < len; k++) {
            char c = input[k];

            if (c == '.') {
                decimalPosition = k +1;
            } else {
                n = (n *10) …
Run Code Online (Sandbox Code Playgroud)

c# performance parsing decimal

10
推荐指数
1
解决办法
1838
查看次数

标签 统计

c# ×2

parsing ×2

.net ×1

decimal ×1

double ×1

performance ×1