Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best practice to make division return double in C#

Tags:

c#

In c# when you want to divide the result of a method such as below, what is the best way to force it to return a double value rather than the default integer.

(int)Math.Ceiling((double)(System.DateTime.DaysInMonth(2009, 1) / 7));

As you can see I need the division to return a double so I can use the ceiling function.

like image 544
Element Avatar asked Jan 28 '09 19:01

Element


People also ask

What is division return C?

In the C Programming Language, the div function divides numerator by denominator. Based on that division calculation, the div function returns a structure containing two members - quotient and remainder.

Can you divide two ints into a double?

Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.

Does division round down in C?

Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.


1 Answers

A division of two int numbers returns an int, truncating any decimal points. This is generally true for other data types as well: arithmetic operations don't change the type of their operands.

To enforce a certain return type, you must therefore convert the operands appropriately. In your particular case, it's actually sufficient to convert one of the operators to double: that way, C# will perform the conversion for the other operand automatically.

You've got the choice: You can explicitly convert either operand. However, since the second operand is a literal, it's better just to make that literal the correct type directly.

This can either be done using a type suffix (d in the case of double) or to write a decimal point behind it. The latter way is generally preferred. in your case:

(int)Math.Ceiling(System.DateTime.DaysInMonth(2009, 1) / 7.0);

Notice that this decimal point notation always yields a double. To make a float, you need to use its type suffix: 7f.

This behaviour of the fundamental operators is the same for nearly all languages out there, by the way. One notable exception: VB, where the division operator generally yields a Double. There's a special integer division operator (\) if that conversion is not desired. Another exception concerns C++ in a weird way: the difference between two pointers of the same type is a ptrdiff_t. This makes sense but it breaks the schema that an operator always yields the same type as its operands. In particular, subtracting two unsigned int does not yield a signed int.

like image 200
2 revs Avatar answered Oct 10 '22 23:10

2 revs