Sunday 4 September 2016

Automatic round enabled while using float in C#

Behavior of float data type over operators.
This example show how automatic Math round happened while using float data type.
We could skip them by casting in to Decimal data type.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Float_Vs_Decimal_Over_Operatores
{
    class Program
    {
        static void Main(string[] args)
        {

            float num1 = 6041.455F;
            float num2 = 223996.3F;
            Console.WriteLine("By variable      :" + (num1 - num2));
            Console.WriteLine("By direct        :" + (6041.455 - 223996.3));

            Decimal sub = ((Decimal)num1 - (Decimal)num2);
            Console.WriteLine("By Casting       :" + sub);

            float subf = (float)((Decimal)num1 - (Decimal)num2);
            Console.WriteLine("By Reverse Casting       :" + subf);


            Console.Read();
        }
    }
}


OutPut:

By variable      :-217954.8
By direct        :-217954.845
By Casting       :-217954.845
By Reverse Casting       :-217954.8