-2

I have some strings in my selection set. I want to convert those to Double and I need to eliminate which is having any letter as a character(A to Z) or anything not possible to convert as double.

the below code is working if the vale is like "564.10" this, and it's getting error if the value like "abvd" or "@#$%dfd".

MText txt = ent as MText;
double txv = Convert.ToDouble(txt.Contents);
string txnv = Convert.ToString(txv + v1.Value);
txt.Contents = txnv;
Rufus L
  • 36,127
  • 5
  • 30
  • 43
  • Do you want to eliminate non-digit characters from the strings and use what's left over, or only use strings that have all digit characters to start with? In other words, if the string was `"23R5.6"` do you want to ignore it, or convert it to `235.6`, or something else? – Rufus L May 22 '20 at 23:05

2 Answers2

4

You can use Double.TryParse

Double.TryParse(txt.Contents, out txv);
AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
  • it's working and I modified my codes as below Double txv; Double.TryParse(txt.Contents, out txv); if (txv != 0) { string txnv = Convert.ToString(txv + v1.Value); txt.Contents = txnv; } – Saifudheen May 23 '20 at 08:13
3

If you want to ignore everything but valid numbers, you should remove them first and then parse the rest. This should work for most cases (including float numbers, as long as there's only one decimal separator):

var input = "qweq14ds.821 dfs";
var decimalSeparator = '.'; // you could get this from current culture
var stringNumber = new string(input.Where(c => char.IsDigit(c) || c == decimalSeparator).ToArray());
double number;
Double.TryParse(stringNumber, out number);

Console.WriteLine(number); // will print 14.821
Pablo CG
  • 818
  • 6
  • 18