How to ensure that a number is always round up to the nearest integer

Yes, this is silly. I never used Math.Ceiling before; so I never even knew what it was for.

In my use case, I’m sending SMS messages via a third party WCF service. It works well, but in my own WCF service, I forgot to limit the length of the message text to 160 characters. That turned out to be a good thing, because they send it anyway, and charge us for the extra messages, which is fine. So all I needed to do was add a parts field to our database table, so that we know how many messages to bill our clients for.

So the requirement is that any multiple of 160 characters gets a part. Anything below 160 characters is one message. Anything greater than 160 characters and less than 320 characters is two messages, and so on…

So, for example, 168 characters is 168 / 160 = 1.05. Math.Round will round down to one. I want it to be two, because any part of a message is a whole message, obviously.

Somebody asked the question on StackOverflow. Actually I found it via this duplicate. Note that I am ignoring the most efficient answer, the “correct” answer if you will… I like the simplest answer, which in my code comes out to:

command.Parameters.AddWithValue("@Parts", (int)Math.Ceiling(message.Length/160D));

So in my example that would be (pseudocode) Math.Ceiling(168/160), which equals 2.

Advertisements

About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s