Fix a Number to N Digits

When dealing with numbers in JavaScript or any other programming language, there is a way to truncate a number after n digits. Unfortunately, there is no such function in Sass. Still, rounding and precision issues do happen when dealing with percentage based grid systems for instance.

Here is a Sass implementation of toFixed():

/// toFixed() function in Sass
/// @author Hugo Giraudel
/// @param {Number} $float - Number to format
/// @param {Number} $digits [2] - Number of digits to leave
/// @return {Number}
@function to-fixed($float, $digits: 2) {
  $sass-precision: 5;
  
  @if $digits > $sass-precision {
    @warn "Sass sets default precision to #{$sass-precision} digits, and there is no way to change that for now."
    + "The returned number will have #{$sass-precision} digits, even if you asked for `#{$digits}`."
    + "See https://github.com/sass/sass/issues/1122 for further informations.";
  }
  
  $pow: pow(10, $digits);
  @return round($float * $pow) / $pow;
}

Note that Sass has a default precision of 5 digits, and there is no way to configure it as of today. Because of this, it is not possible for Sass to compute a number with more than 5 digits, no matter the number given to the function as $digits.

Also, this function requires a pow function that does not come native with Sass (yet). It exists in Compass, but if you do not use Compass or any other library that provides it, you might need your own pow function. Fortunately, it is quite easy to implement:

/// Power function
/// @param {Number} $x
/// @param {Number} $n
/// @return {Number}
@function pow($x, $n) {
  $ret: 1;
    
  @if $n >= 0 {
    @for $i from 1 through $n {
      $ret: $ret * $x;
    } 
  } @else {
    @for $i from $n to 0 {
      $ret: $ret / $x;
    }
  }
  
  @return $ret;
}

Submit 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.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag