Rounding Up - C#

Asked

Viewed 1,167 times

5

I use a program to correct my stock of the tax file sped that I send to revenue. But I’m in trouble because unit products are coming out with broken value.

Example below, the product had (50) units after q I pass the program it gets broken value (13,089) I wanted to round up (note that I am dividing by 3,82)

|H010|7506195153574|UN|50|5,93|296,5|0|||001|296,5| (original)

|H010|7506195153574|UN|13,089|5,93|77,62|0|||001|296,5| (alterado)

my code:

string[] strArray = File.ReadAllLines(@"original.txt");
StreamWriter writer = File.AppendText(@"alterado.txt");
foreach (string str in strArray)
{
    string[] strArray2 = str.Split(new char[] { '|' });
    if (strArray2[1] == "H010")
    {
        strArray2[4] = Math.Round((decimal)((Convert.ToDecimal(strArray2[4]) / 382M) * 100M),3).ToString();
        string str2 = string.Join("|", strArray2);
        writer.WriteLine(str2);
    }
}

Just warning I am studying C# for a little while and I will start my course only next year, I’m managing with tutorial on the net, but I don’t understand anything in the logical part. :( :(

  • I don’t understand what the problem is. What you show in the changed, is all wrong, is this?

1 answer

6

Use Math.Ceiling instead of Math.Round:

strArray2[4] = Math.Ceiling(Convert.ToDecimal(strArray2[4]) / 382M * 100M).ToString();

Ceiling always round up. Round rounded up only if the decimal part is greater than 0.5.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.