thednp thednp - 4 months ago 35
Less Question

LESS: how to check value is integer like in javascript value%1 == 0

How to tell in a LESS function/mixin that a number is integer similar to Javascript's usual function:

var data = 22;

if(data % 1 === 0){
// yes it's an integer.
}

Answer

Use a combination of guarded namespaces and the floor function.

Here is a live demo on codepen. Try changing the value of @my_val to something without a fractional part (this includes values like 1.0) and watch the text turn green.


LESS:

@my_val: 55.6;

#my_text {
  color: red;
  /* if @my_val has no fractional part */
  & when (@my_val = floor(@my_val)) {
    color: green;
  }
}

HTML:

<span id="my_text">Green if integer, red otherwise.</span>