# 1, 2, 3 rule

1. Mar 18, 2004

### completenewbie

Hi, its my first post, so don't be too hard on me. Here's my dilemma:

I'm trying to write a computer program, to return a number with it's apropriate suffix. (ie: 1=1st, 2=2nd, 3=3rd, etc.) Forget the programming aspect for a minute, all I'm interested in is the logic. If X=answer, I can integer divide (mod) X by 10 and I get a number between 0 and 9 (ie: 21mod10=1, 33mod10=3, 40mod10=0, etc.). Then I can assign 1= st, 2=nd, 3=rd, and everything else=th. The logic works except for 11, 12, and 13. Using this logic, I get 11st, 12nd, and 13rd. How can I modify my logic to make it work?

2. Mar 18, 2004

### Chen

Take the number and divide it by then. If the {answer} mod 10 equals 1, you need to give the number "th". Otherwise, follow the logic you posted above.

3. Mar 18, 2004

### completenewbie

I'm not following the "Take number and divide by then." part of the post. Can you clarify that a little? Thanks.

4. Mar 18, 2004

### Chen

I'm sorry, I meant to say divide it by ten.

5. Mar 18, 2004

### completenewbie

That thoery doesn't seem to make sense to me:
If X=11 Then X/10=1.1
If X=111 Then X/10=11
If X=33 Then X/10=3.3
If X=333 Then X/10=33

I guess I'm not following you, can you explain that agian.

6. Mar 18, 2004

### Chen

You need to take the number and divide it by ten. You then need to divide it again by 10, and if the remainder (mod) is 1 it means that the 2nd digit of the number is 1, so you need to use the "th" suffix. For any other rules, the normal rules (in your first post) apply.

In PHP this would like this:
PHP:
function get_suffix($number) { if (($number / 10) % 10 == 1) {
return 'th';
} else {
switch ($number % 10) { case 1: return 'st'; break; case 2: return 'nd'; break; case 3: return 'rd'; break; default: return 'th'; break; } } } You can make it even more efficient (but less readable): PHP: function get_suffix($number) {
if (($number / 10) % 10 != 1) { switch ($number % 10) {
case 1:
return 'st';
case 2:
return 'nd';
case 3:
return 'rd';
}
}
return 'th';
}
But I'm not here to teach PHP. :)

7. Mar 18, 2004

### confutatis

Here's one way to do it:

- X = X mod 100
- if X > 3 and X < 21 then make it 'th'
- else apply your rule

Here's another:

- X = (X + 90) mod 100
- if X < 4 then X = X + 4
- apply your rule

I like the second one better - it illustrates how computers can do trivial things in very confusing ways...

8. Mar 18, 2004

### completenewbie

And the light goes on.... ding.

Thanks guys.

9. Mar 18, 2004

### completenewbie

I could also do this:

A=answer
X=Amod100
Y=Amod10
if X=11 or X=12 or X=13 then add "th"
if Y>3 then add "th"
if Y=0 then add "th"
if Y=1 then add "st"
if Y=2 then add "nd"
if Y=3 then add "rd"

The actual code will look different, but you get the idea. Thanks for steering me in the right direction.

Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook