简体   繁体   English

C# 如果所有字母都是数字,则字符串为 Double

[英]C# String to Double if all letters are numbers

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.我想将它们转换为 Double 并且我需要消除将任何字母作为字符(A 到 Z)或任何无法转换为 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".如果 vale 类似于“564.10”,则以下代码有效,如果值类似于“abvd”或“@#$%dfd”,则会出错。

MText txt = ent as MText;
double txv = Convert.ToDouble(txt.Contents);
string txnv = Convert.ToString(txv + v1.Value);
txt.Contents = txnv;

You can use Double.TryParse您可以使用Double.TryParse

Double.TryParse(txt.Contents, out txv);

If you want to ignore everything but valid numbers, you should remove them first and then parse the rest.如果您想忽略除有效数字之外的所有内容,则应先将其删除,然后解析 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

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

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