我必須打開檔案,找到所有小數,洗掉小數部分,四舍五入并在文本中替換。結果文本應列印在控制臺中。我試圖這樣做,但我所做的唯一一件事就是洗掉小數部分。請告訴我如何舍入它們并在結果文本中替換。這是我的代碼:
Console.WriteLine("Enter path to first file:");
String path1 = Console.ReadLine();
string text = File.ReadAllText(path1);
string pattern = @"(\d )\.\d ";
if(File.Exists(path1) ){
foreach(string phrase in Regex.Split(text, pattern)){
Console.Write(phrase);
}
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
uj5u.com熱心網友回復:
您可以使用@"\d ([\.\,]\d )"模式來捕獲具有任意小數位數的每個數字。然后Regex.Replace與MatchEvaluator 一起使用,其中將捕獲的值決議為double然后通過簡單的“切割”小數ToString("F0")(檢查固定點格式)。
下面的示例包括在多載的幫助下使用逗號,或.分數分隔符的小數double.TryParse,我們可以在其中指定NumberStyles.Anyand CultureInfo.InvariantCulture(來自System.Globalization命名空間)以及將逗號簡單替換,為 dot .。也適用于負數(例如 -0.98765 示例):
var input = "I have 11.23$ and can spend 20,01 of it. "
"Melons cost 01.25$ per -0.98765 kg, "
"but my mom ordered me to buy 1234.56789 kg. "
"Please do something with that decimals.";
var result = Regex.Replace(input, @"\d ([\.\,]\d )", (match) =>
double.TryParse(match.Value.Replace(",", "."), NumberStyles.Any, CultureInfo.InvariantCulture, out double value)
? value.ToString("F0")
: match.Value);
// Result:
// I have 11$ and can spend 20 of it.
// Melons cost 1$ per -1 kg,
// but my mom ordered me to buy 1235 kg.
// Please do something with that decimals.
On"Aaaa 50.05 bbbb 82.52 cccc 6.8888"也適用于"Aaaa 50 bbbb 83 cccc 7".
uj5u.com熱心網友回復:
您可以Math.Round在所有可以轉換Regex.Replace的匹配項上使用,并使用匹配評估器作為替換:
var text = "Aaaa 50.05 bbbb 82.52 cccc 6.8888";
var pattern = @"\d \.\d ";
var result = Regex.Replace(text, pattern, x => $"{Math.Round(Double.Parse(x.Value))}");
Console.WriteLine(result); // => Aaaa 50 bbbb 83 cccc 7
請參閱C# 演示。
在\d \.\d 正則運算式是簡單,一個或多個數字,火柴.和一個或多個數字。Double.Parse(x.Value)將找到的值轉換為Double,然后Math.Round對數字進行四舍五入。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/372168.html
上一篇:如何從MemoryStream轉換為FileStream以傳遞給MSGraph?
下一篇:如何從多個陣列中找到單個字串?
