Fix a Number to N Digits

Avatar of Kitty Giraudel
Kitty Giraudel on (Updated on )

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 Kitty 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 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;