chromedude
chromedude

Reputation: 4302

How do you Javascript charAt() a integer?

I have an array. One of the values in that array responses[1] is an integer. This integer can be from 1 to whatever number you want. I need to get the last number in the integer and determine based on that number if I should end the number with 'st', 'nd', 'rd', or 'th'. How do I do that? I tried:

var placeEnding;
var placeInt = response[1]; //101
var stringInt = placeInt.toString();
var lastInt = stringInt.charAt(stringInt.length-1);
if (lastInt == '1'){
    placeEnding = 'st';
} else if (lastInt == '2'){
    placeEnding = 'nd';
} else if (lastInt == '3'){
    placeEnding = 'rd';
} else {
    placeEnding = 'th';
}

but that did not work. Every time I tried printing placeEnding it was always 'th' no matter if it should have been 'st', 'rd', or 'nd'. When I tried printing placeInt, stringInt, or lastInt they all printed as " instead of the number. Why is this so? When I print responses[1] later on in the script I have no problem getting the right answer.

Upvotes: 1

Views: 4638

Answers (5)

mar77i
mar77i

Reputation: 120

I noticed I wanted to use the st/nd/rd/th in dates, and just noticed there is an exception between 10 and 20 with the eleventh, twelfth and so on, so I came to this conclusion:

if (n % 10 === 1 && (n % 100) - 1 !== 10) {
    return "st";
} else if (n % 10 === 2 && (n % 100) - 2 !== 10) {
    return "nd";
} else if (n % 10 === 3 && (n % 100) - 3 !== 10) {
    return "rd";
}
return "th";

Upvotes: 1

Joseph Silber
Joseph Silber

Reputation: 220026

Here you go:

var ends = {
    '1': 'st',
    '2': 'nd',
    '3': 'rd'
}

response[1] += ends[ response[1].toString().split('').pop() ] || 'th';

As others have pointed out, using modulus 10 is more efficient:

response[1] += ends[ parseInt(response[1], 10) % 10 ] || 'th';

However, this'll break if the number has a decimal in it. If you think it might, use the previous solution.

Upvotes: 5

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57670

In my rhino console.

js> (82434).toString().match(/\d$/)
4

Upvotes: 2

tzaman
tzaman

Reputation: 47830

If all you want is the last digit, just use the modulus operator: 123456 % 10 == 6
No need to bother with string conversions or anything.

Upvotes: 5

Brij
Brij

Reputation: 6122

Alternate way to get lastInt is:

 var lastInt = parseInt(stringInt)%10;
switch lastInt {
    case 1:
        placeEnding = 'st';
        break;
    case 2:
        placeEnding = 'nd';
        break;
    case 3:
        placeEnding = 'rd';
        break;
    default:
        placeEnding = 'th';
}

Upvotes: 1

Related Questions