How to parse back the result of string.Format
Let's say I have a number (e.g. double) and transform it using some format string into a string variable :
var s开发者_如何学Ctr = string.Format("{0:0%}", 0.256);
(the content of the str variable is in this case "26%"
). Is there any way to parse this string back into the number ?
I'm aware that depending on the format string the lossless conversion back might not be possible - just as in this case 0.26
is the best I can get because some information (3rd decimal place) was simply lost in the formatting. But even getting 0.26
from a combination of the format string "{0:0%}"
and the string 26%
would be great if it's possible in some automatic way.
I believe that RegEx is the best standard tool for your purposes. There is plenty of scanf implementations for .net, but I think writing your own regular expression is better.
Your value is of some type (int
, double
, decimal
). All of these functions have a Parse()
or TryParse()
function like Decimal.Parse(). And to say, in what format this number is (e.g. different usage of comma and point in english and german) you can provide an IFormatProvider
(which is easiest available as a CultureInfo
).
Update
After a little more searching i found these questions at SO:
- Parse a string containing percent sign into decimal
- How to convert percentage string to double?
and also some searching at the web didn't reveal any usable stuff. So it seems that here is a really missing feature within the .Net framework and all you can do is write something for yourself (or take one of the suggested solutions in the questions above).
So sorry, for my first wrong answer, but it seems, that there doesn't really exists something out of the (.net framework) box.
精彩评论