Correctly Adding Unit to Number

When converting a unitless number to a length, duration, angle or whatever, people tend to simply append the unit as a string, like this:

$value: 42;
$length: $value + px;
// 42px

While this method works, it is far from ideal because it results in implicitly casting the initial value as a string. Indeed, if you try doing math with the $length value from now on, you'll see that Sass quickly throws an error because it cannot do math operators with a string.

To work around this issue, there are two ways of doing this properly:

$value: 42;
$length: $value + 0px;
// 42px
$value: 42;
$length: $value * 1px;
// 42px

Any of those methods will correctly produce a number as expected and not a string.


  1. User Avatar
    Permalink to comment#

    I use the last method, and it works fine.

  2. User Avatar
    Linus Miller

    Multiplication is a far more complicated operation for a computer to do that addition. So always use the first one.

    • User Avatar
      Permalink to comment#


    • User Avatar
      Permalink to comment#

      It’s not far more complicated. Addition is linear and multiplication is not far from that. For such small number it’s just one cycle anyway, so it really does not matter.

  3. User Avatar
    Permalink to comment#

    $value3:$value1+$value2; // 1px2px

    • User Avatar
      Permalink to comment#

      Isn’t what you were expecting?
      This is out of the scope as they were trying to add an number to its unit!

Leave a Comment

Posting Code!

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.