Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Ceiling weird behaviour

Tags:

c#

I'm having a weird problem and I'm pretty sure I'm missing something.

decimal pages = Math.Ceiling((decimal)(927/1027));
MessageBox.Show(pages.ToString());

927/1027 = 0.902..... so this should return 1 right?

Instead I get 0.

But when I directly input the value to Ceiling,

decimal pages = Math.Ceiling((decimal)(0.902));
MessageBox.Show(pages.ToString());

I get 1 as expected. Am I missing something?

like image 388
Nadeeja Avatar asked Dec 08 '22 19:12

Nadeeja


1 Answers

927/1027 is an integer expression that evaluates to the int with value 0.

If you want a decimal calculation then you should do it like this:

Math.Ceiling(927m/1027m);

The m suffix indicates a literal of type decimal.

But that itself would be somewhat odd since Math.Ceiling receives a floating point parameter as input. So, if you are using Math.Ceiling then I think that you really want to use floating point division. Like this:

Math.Ceiling(927.0/1027.0);
like image 100
David Heffernan Avatar answered Dec 11 '22 09:12

David Heffernan