tags:

views:

61

answers:

2

I'm looking for an algorithm to return the number of parts per 100.

For example, if the part is between 1 to 100 then it return 1. If the part is between 101 to 200 then it should return 2. Final example, if the part is 357 it should return 4.

A simple division will not work and tried modulo but cannot get it to give me the right answer. Can someone help me with this?

+3  A: 

You can simply divide by 100 and ceil the value.

What language are you using?

PHP example: $part = ceil($number/100);

NullUserException
Warning: this works if the division is floating point division, but not if it's integer division, e.g. in Java, `Math.ceil(234/100)` will return `2.0`, not `3.0`. Use `100.0` rather than `100` in languages where it makes a difference.
Simon Nickerson
In Java you can do `Math.ceil(1.0*234/100)` to force it to use floating point.
NullUserException
The ceil() function was exactly what I was looking for. Thanks!
munchine
Indeed, once you're aware of the problem there are lots of solutions. But until you're aware, it can be confusing.
Simon Nickerson
A: 

Language is important here but usually you can either use a ceiling function, or cast the numbers as integers and add 1 to it like I have below for C++

int parts_per_hundred(int value) {

// value / 100 will give you an integer. 
// we subtract 1 from the value so multiples of 100 are part of their number not the next highest.
int result = ((value - 1) / 100 ) + 1;

return result;

}
Kinglink
parts_per_hundred(0) returns 1.
waxwing