Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

See code below

 

string str = "APR 12.34% APR";

string aDecimal;

aDecimal = Decimal.Parse(str, System.Globalization.NumberStyles.Any).ToString();

Response.Write(aDecimal);

 

Here I am trying to retrieve the numeric part from the string str ? and is not working.

 

Is there any other idea to achieve the expected result

 

Thank u in advance

ima
Posted

Parse methods

 

The Parse methods can only handle whitespace, not other characters. You therefore have to strip out all characters except numerics (and whitespace). You could do this with regular expressions, or using something like this:

 

//Untested code
int pos = str.IndexOfAny("0123456789".ToCharArray());
if (pos > -1) {
   str = str.Substring(pos);
   pos = str.LastIndexOfAny("0123456789".ToCharArray());
   str = str.Substring(0, pos + 1);

   aDecimal = Decimal.Parse(str, System.Globalization.NumberStyles.Any).ToString();
}

 

Note that this won't work if the string contains multiple numbers, but it should give you an idea of what needs to be done. I have to say that using the name aDecimal for a string variable is a bit strange.

 

Good luck :cool:

Never trouble another for what you can do for yourself.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...