简体   繁体   English

复杂的字符串到双重转换

[英]complex string to double conversion

I have strings in a XML file that ment to be doubles (or float) such as: 我在XML文件中有字符串,可以是双精度(或浮点数),例如:

<VIPair>
<voltage>+100mV</voltage>
<current>+1.05pA</current>
</VIPair>

<VIPair>
<voltage>+5.00mV</voltage>
<current>+0.0035nA</current>
</VIPair>

The first pair will be "0.1" Volt and "0.00000000000105" Ampere. 第一对将是“0.1”伏和“0.00000000000105”安培。 The second pair would be "0.005" Volt and "0.000000000035" Ampere. 第二对是“0.005”伏和“0.000000000035”安培。

How can I convert them to double of float in C#? 如何在C#中将它们转换为float的两倍? Thanks. 谢谢。

PS: I already can read them from xml file and at the moment I retrive them as string. PS:我已经可以从xml文件中读取它们,现在我将它们作为字符串进行检索。

Try with this: 试试这个:

// Read string (if you do not want to use xml)
string test = "<voltage>+100mV</voltage>";
string measure = test.Substring(test.IndexOf('>')+1);
measure = measure.Substring(0, measure.IndexOf('<')-1);

// Extract measure unit
string um = measure.Substring(measure.Length - 1);
measure = measure.Substring(0, measure.Length - 1);
// Get value
double val = Double.Parse(measure);
// Convert value according to measure unit
switch (um)
{
    case "G": val *= 1E9; break;
    case "M": val *= 1E6; break;
    case "k": val *= 1E3; break;
    case "m": val /= 1E3; break;
    case "u": val /= 1E6; break;
    case "n": val /= 1E9; break;
    case "p": val /= 1E12; break;
}

Hi here is another version of what Marco has written. 嗨,这是Marco写的另一个版本。

            string str = "1pV";
            double factor;
            double value;
            switch (str[str.Length-2])
            {
                case 'M': factor = 1E6; break;
                case 'm': factor = 1E-3; break;
                case 'n': factor = 1E-9; break;
                case 'p': factor = 1E-12; break;
                default:
                    factor = 1; break;
            }
            value = double.Parse(str.Substring(0,str.Length-2)) * factor;

Assuming that the html text is already available to you. 假设html文本已经可供您使用。 I have tried to do the same thing with one substring, switch case with characters instead of strings(This is a bit faster to comparing strings) and a double.parse. 我试图用一个子字符串做同样的事情,用字符而不是字符串切换大小写(比较字符串要快一点)和double.parse。 Hope someone comes up with a better version than this. 希望有人能提出比这更好的版本。

使用string.Substringstring.Remove()方法删除后缀字符串mVnA并使用double.TryParse()方法将字符串解析为double。

If your values always have 2 chars on the end you could simple remove these and parse the number. 如果你的值总是有两个字符,你可以简单地删除它们并解析数字。

var newstring = fullstring.Substring(0, fullstring.Length - 2);
var number = double.Parse(newstring);

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

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