简体   繁体   中英

How to Use substring in c#?

I have -$2.00 as the string. I am trying to change it to decimal by removing - and $ using substring, but I am doing it wrong. Can someone help me?

Thanks.

string m = "-$2.00";
decimal d = Math.Abs(Decimal.Parse(m, NumberStyles.Currency));

Substring will return a new string. I suspect your issue is likely from trying to mutate the string in place, which does not work.

You can do:

string result = original.Substring(2);
decimal value = decimal.Parse(result);

Depending on how the input string is generated, you may want to use decimal.TryParse instead, or some other routine with better error handling.

Don't.

Instead, you should make .Net do the dirty work for you:

Decimal value = Decimal.Parse("-$2.00", NumberStyles.Currency);

If, for some reason, you don't want a negative number, call Math.Abs .

所有字符串操作都返回一个新字符串,因为字符串是不可变的

I wouldn't use substring if you can avoid it. It would be much simpler to do something like:

string result = original.Replace("$", "").Replace("-", "");

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