Home > Enterprise >  How to remove decimals from file (round them)?
How to remove decimals from file (round them)?

Time:12-03

I have to open file, find all decimals, remove decimal part, round them and replace in the text. Result text should be print in the Console. I tried to do it, but the only thing I made was to remove the decimal part. Please tell me how to round them and replace in the result text. Here is my code:

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);      
        }

CodePudding user response:

You can use @"\d ([\.\,]\d )" pattern to capture each number with any amount of decimals. Then use Regex.Replace with MatchEvaluator, where parse captured value as double then "cut" decimals by simple ToString("F0") (check about Fixed-point format).

Example below include decimals with comma , or . fraction separators with help of double.TryParse overload, where we can specify NumberStyles.Any and CultureInfo.InvariantCulture (from System.Globalization namespace) and simple replacement of comma , to dot .. Also works with negative numbers (e.g. -0.98765 in example):

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" would work too with result of "Aaaa 50 bbbb 83 cccc 7".

CodePudding user response:

You can use Math.Round on all matches that you can transform using Regex.Replace and a match evaluator as the replacement:

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

See the C# demo.

The \d \.\d regex is simple, it matches one or more digits, . and one or more digits. Double.Parse(x.Value) converts the found value to a Double, and then Math.Round rounds the number.

  • Related