Dividing


/ Division

This is the normal division operator however in C# this can often give you unexpected results.
When you divide an integer by another integer, C# will perform Integer Division

Console.WriteLine( 4/3 );    // 1 

When you divide an integer by a floating point, C# will perform Decimal Division

Console.WriteLine( 4/3.0 );    // 1.33333333 (? How many dp ) 

When you divide a floating point by an integer, C# will perform Decimal Division

Console.WriteLine( 4.0/3 );    // 1.33333333 (? How many dp ) 

Always Returning Decimals

If you want to divide an integer by an integer and perform decimal division you must explicitly convert one of the integers to a float, double or decimal.

Console.WriteLine( (float)4/3 );      // 1.333333333333333333 
Console.WriteLine( (double)4/3 ); // 1.3333333 (16 dp)
Console.WriteLine( (decimal)4/3 ); // 1.3333333 (28 dp)

You cannot combine data types "double" and "decimal"

myDecimal = myDecimal / myDouble;   // convert the double to decimal 

Dividing Double with Integer
If you have a double data type containing 1234567




© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext