How to rounds numbers in C#

2 Answers

0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            double d = 123.45;

            Console.WriteLine(Math.Round(d, 1, MidpointRounding.AwayFromZero));

            Console.WriteLine(Math.Round(d, 1, MidpointRounding.ToEven));

            Console.WriteLine(Math.Round(d));
        }
    }
}


/*
run:
    
123.5
123.4
123

*/

 



answered Feb 13, 2017 by avibootz
edited Feb 13, 2017 by avibootz
0 votes
using System;

namespace ConsoleApplication_C_Sharp
{
    class Program
    {
        static void Main(string[] args)
        {
            double d = 125.101;

            Console.WriteLine(Math.Round(d, 1, MidpointRounding.AwayFromZero));
            Console.WriteLine(Math.Round(d, 1, MidpointRounding.ToEven));
            Console.WriteLine(Math.Round(d, 1));
            Console.WriteLine(Math.Round(d) + "\n");
            
            Console.WriteLine(Math.Round(d, 2, MidpointRounding.AwayFromZero));
            Console.WriteLine(Math.Round(d, 2, MidpointRounding.ToEven));
            Console.WriteLine(Math.Round(d, 2) + "\n");

            d = 125.109;
            Console.WriteLine(Math.Round(d, 2, MidpointRounding.AwayFromZero));
            Console.WriteLine(Math.Round(d, 2, MidpointRounding.ToEven));
            Console.WriteLine(Math.Round(d, 2));
            Console.WriteLine(Math.Round(d));
        }
    }
}


/*
run:
    
125.1
125.1
125.1
125

125.1
125.1
125.1

125.11
125.11
125.11
125

*/

 



answered Feb 13, 2017 by avibootz
edited Feb 13, 2017 by avibootz

Related questions

2 answers 201 views
201 views asked Feb 13, 2017 by avibootz
1 answer 172 views
172 views asked Jan 12, 2017 by avibootz
1 answer 143 views
143 views asked Jan 12, 2017 by avibootz
...