How can I convert the following string:
string x = "text text 542050.0000 text 245.00 text";
to this: "text text 542050 text 245 text"
i want to keep all text in this string , just remove decimal part of numbers
If you want to solve for the general case of removing decimals in strings, you can use RegEx:
var input = "text text 542050.0000 text text";
var regex = "((?<keep>[0-9]+)\\.[0-9]+)";
var matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator((m) => m.Groups["keep"].Value);
var output = System.Text.RegularExpressions.Regex.Replace(input, regex, matchEvaluator);
The RegEx will match all decimals, and return the whole part as a replacement. Note that if you have a string like 5.2.1 then this will result in "5.1".
If you want to output a specific number of decimal places you could try this:
var input = "text text 542050.0129 text text";
var regex = "([0-9]+\\.[0-9]+)";
var matchEvaluator = new System.Text.RegularExpressions.MatchEvaluator((m) => {
var decimalValue = double.Parse(m.Groups[0].Value);
return String.Format("{0:0.000}", Math.Round(decimalValue, 3));
});
var output = System.Text.RegularExpressions.Regex.Replace(input, regex, matchEvaluator);
In my example, I've rounded to 3 dp and formatted with 3 dp (formatting to ensure that it always outputs .000 - you can remove this step if you don't need it). For "542050.0129" above, it would output "542050.013"
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.