Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If number ends with 1 do something

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?

like image 503
valek Avatar asked Dec 06 '13 20:12

valek


4 Answers

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.

like image 147
Shad Avatar answered Oct 21 '22 08:10

Shad


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.

like image 30
aKzenT Avatar answered Oct 21 '22 08:10

aKzenT


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)
like image 8
AaronLS Avatar answered Oct 21 '22 08:10

AaronLS


this can be solved by single line

return (day % 10 == 1) ? 'dan' : 'dana';
like image 1
Manivannan Avatar answered Oct 21 '22 08:10

Manivannan