简体   繁体   中英

convert multi variable from string to decimal in c#.net in asp.net threw an exception of type 'System.FormatException'

i have 2 or maybe more than 2 string variable like below

string a = csvalue[7].Replace(" ", ""); //a="‏120641"
string b = csvalue[9].Replace(" ", "") ;//b="‏"221707‏‏‏‏
decimal result = Convert.ToDecimal(a) + Convert.ToDecimal(b)

but it have exception:" threw an exception of type 'System.FormatException'"

i try

       enter code here 
       string one = "‏120641‏‏‏‏";
        string two = "‏221707‏‏‏‏";
        string three = "123548";
       
        Double iOne = 0;
        Double iTwo = 0;
        Double ithree = 0;

        Double.TryParse(one, out iOne);
        Double.TryParse(two, out iTwo);
        Double.TryParse(three, out ithree);

and it dosent work for iOne,iTwo please help me

There are some (invisible) unicode chars which are not digits, so cannot be parsed. You could remove them for example with Linq and char.IsDigit :

using System;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        string one = "‏120641‏‏‏‏";
        string two = "‏221707‏‏‏‏";
        string three = "123548";
        one = new string(one.Where(char.IsDigit).ToArray());
        two = new string(two.Where(char.IsDigit).ToArray());
        three = new string(three.Where(char.IsDigit).ToArray());
       
        Double iOne = 0;
        Double iTwo = 0;
        Double ithree = 0;

        Double.TryParse(one, out iOne);
        Double.TryParse(two, out iTwo);
        Double.TryParse(three, out ithree);
        Console.WriteLine(iOne);
        Console.WriteLine(iTwo);
        Console.WriteLine(ithree);
    }
}

.Net Fiddle

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