33

I want to make something like this:

if(day==1 || day==11 || day==21 || day==31 || day==41 ......){
    result="dan";
}
else{
    result="dana";
}

How can i do that with every number that ends with one and of course without writing all numbers?

JJJ
  • 32,902
  • 20
  • 89
  • 102
valek
  • 1,365
  • 16
  • 27
  • 4
    I removed mentions of jQuery which is a library for manipulating the DOM, not doing math. – JJJ Dec 06 '13 at 20:54
  • 1
    You could also turn the number into a string and use the slice() method to check the last value. Not sure which would be more performant, but it likely doesn't matter. – ernie Dec 06 '13 at 22:19
  • 1
    @Juhana Yeah right, not gonna fall with that, jQurery doesn't know math... Dude jQuery is math! – gdoron Dec 10 '13 at 23:54

5 Answers5

60

Just check the remainder of division by 10:

if (day % 10 == 1) { 
  result = "dan";
} else {
  result = "dana";
}

% is the "Modulo" or "Modulus" Operator, unless you're using JavaScript, in which case it is a simple remainder operator (not a true modulo). It divides the two numbers, and returns the remainder.

Shad
  • 4,423
  • 3
  • 36
  • 37
17

You can check the remainder of a division by 10 using the Modulus operator.

if (day % 10 == 1)
{ 
   result = "dan";
}
else
{
   result = "dana";
}

Or if you want to avoid a normal if:

result = "dan" + (day % 10 == 1 ? "" : "a");

% is the Javascript Modulus operator. It gives you the remainder of a division:

Example:

11 / 10 = 1 with remainder 1.
21 / 10 = 2 with remainder 1.
31 / 10 = 3 with remainder 1.
...

See this answer: What does % do in JavaScript? for a detailed explication of what the operator does.

Community
  • 1
  • 1
aKzenT
  • 7,775
  • 2
  • 36
  • 65
7

Modulus operator. You can research it but basically you want to detect if a number when divided by 10 has a remainder of 1:

if( day%10 == 1)
AaronLS
  • 37,329
  • 20
  • 143
  • 202
1

this can be solved by single line

return (day % 10 == 1) ? 'dan' : 'dana';
ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Manivannan
  • 3,074
  • 3
  • 21
  • 32
0

You can convert the number to a string and use String.prototype.endsWith().

const number = 151

const isMatch = number.toString().endsWith('1')

let result = ''

if (isMatch) {
    result = 'dan'
} else {
    result = 'dana'
}

I'm using it in some code that sets the ordinal. For example, if you want to display 1st, 2nd, 3rd, or 4th:

        let ordinal = 'th';
        if (number.toString().endsWith('1')) {
            ordinal = 'st'
        }
        if (number.toString().endsWith('2')) {
            ordinal = 'nd'
        }
        if (number.toString().endsWith('3')) {
            ordinal = 'rd'
        }
agm1984
  • 15,500
  • 6
  • 89
  • 113