Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Math.Ceiling with ints in C#

Tags:

c#

double

decimal

I am trying to take a file and split it into 512kb chunks. To calculate the number of chunks, I need to do some basic math. For some reason, I am having some data loss issues. I can't figure out what I'm doing wrong. I currently have:

int chunkSize = 524288;  // 512kb
int fileByteCount = GetFileSizeInBytes();
decimal result = ((decimal)(fileByteCount)) / ((decimal)(chunkSize));
int packetCount = Math.Ceiling(result);   // Doesn't work.

I can't use Math.Ceiling because it requires a double. But, I think, I need to use a decimal to do the math. What am I doing wrong? How do I do this basic math operation?

like image 992
user609886 Avatar asked Aug 10 '12 13:08

user609886


People also ask

Does ceil work on INT?

The ceil() function returns the integer as a double value.

What does ceil () do in C?

C ceil() The ceil() function computes the nearest integer greater than the argument passed.

What Math ceil () method does *?

The Math. ceil() function always rounds up and returns the smaller integer greater than or equal to a given number.


1 Answers

Use integer math:

int chunkSize = 524288;  // 512kb
int fileByteCount = GetFileSizeInBytes();
int packetCount = (fileByteCount + chunkSize - 1) / chunkSize;

Note that a file size should really be long, transferring files larger than 2 gigabytes is not unusual.

like image 134
Hans Passant Avatar answered Oct 26 '22 18:10

Hans Passant