简体   繁体   中英

Convert a string with commas to double

I have a string like this: 99 365 25,633 gghddhdf 35

I need all the numbers in an array. My problem is how do I handle 25,633 because of the ','. How I can get this number too? My code is:

public string campDiff(string lineStr1, string lineStr2)
{
    int size;
    string sum = null;
    double num1;
    double num2;
    double number;

    string[] lineArr1 = lineStr1.Split(' '); ;
    string[] lineArr2 = lineStr2.Split(' ');

    if (lineArr1.Length > lineArr2.Length)
    {
        size = lineArr1.Length;
    }
    else
    {
        size = lineArr2.Length;
    }

    for (int i = 0; i < size; i++)
    {

        if (Double.TryParse(lineArr1[i], out num1))
        {


            if (Double.TryParse(lineArr2[i], out num2))
            {

                number = num2 - num1;
                if (number > 0)
                {
                    sum = Convert.ToString(number);
                    return sum;
                }
            }
        }
    }
    return sum;
}

But it's skipping over the number with the commas.

There are a lot of possible solutions. Although, the best one I think is to set your CultureInfo to Invariant and then replace all commas with dots. For example:

Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
string number = "3,2";
double d = double.Parse(number.Replace(",", "."));
Console.WriteLine(d);

In your code that would be made like this:

    double[] numbers1 = 
        lineStr1.Replace(",", ".")
                    .Split(new char[0], StringSplitOptions.RemoveEmptyEntries)
                    .Select(s =>
                    {
                        double value;
                        bool success = double.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out value);

                        return new { value, success };
                    })
                    .Where(p => p.success)
                    .Select(p => p.value)
                    .ToArray();

    double[] numbers2 = 
        lineStr2.Replace(",", ".")
                    .Split(new char[0], StringSplitOptions.RemoveEmptyEntries)
                    .Select(s =>
                    {
                        double value;
                        bool success = double.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out value);

                        return new { value, success };
                    })
                    .Where(p => p.success)
                    .Select(p => p.value)
                    .ToArray();

Now you have two arrays numbers1 and numbers2 with all possible numbers parsed from the two strings lineStr1 and lineStr2 . You decide what to do with them as I cannot understand fully the purpose of your method.

( Thanks to all the guys in the comments for making me edit my answer. )

I assume you have only one string that contains , in your string, then you can split your string with white space, get the item contains that character, then parse it to double with a culture that has , as a NumberDecimalSeparator like ( tr-TR ).

var str = "99 365 25,633 gghddhdf 35";
var element = str.Split(' ').Where(s => s.Contains(',')).ToArray()[0];

double d = double.Parse(element, CultureInfo.GetCultureInfo("tr-TR"));

I used tr-TR because it's my current culture. You can Clone your CurrentCulture and set it's NumberDecimalSeparator property to , if it is not.

Simply check if the current lineArrX IsLetter or not before doing the sub.

public class IsLetterSample {
public static void Main() {
    char ch = '8';

    Console.WriteLine(Char.IsLetter(ch));                   // False
    Console.WriteLine(Char.IsLetter("sample string", 7));   // True
}

您可以先对字符串进行正则表达式

 Regex.Replace(input, "[^0-9]+", string.Empty);

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