Skip to content

Instantly share code, notes, and snippets.

@zakmac
Last active August 29, 2015 14:24
Show Gist options
  • Save zakmac/b982b50ed4dd6c25eaf9 to your computer and use it in GitHub Desktop.
Save zakmac/b982b50ed4dd6c25eaf9 to your computer and use it in GitHub Desktop.
SASS function to round a decimal to n places (n being < 6)
@charset "UTF-8";
/**
SASS NUMBER FUDGING FUNCTION
About: A SASS 3.2 compatible function that rounds a number to an accuracy of n decimal places
Author: Zak MacDonald <http://github.com/zakmac>
JSBin: http://jsbin.com/foreda/edit?css
**/
@function fudge($number, $places: 0) {
$fraction: 10;
$number: $number;
@if $places == 0 {
@return round($number);
} @else {
@if $places > 5 {
$places: 5;
}
// how sweet life could be with some simple trig... no loop necessary
// $fraction: (10 ^ $places);
// @return round($number * $fraction) / $fraction;
@for $i from 1 to $places {
$fraction: $fraction * 10;
}
@return round($number * $fraction) / $fraction;
}
}
/**
SASS NUMBER FUDGING FUNCTION
About: A SASS 3.2 compatible function that rounds a number to an accuracy of n decimal places
Author: Zak MacDonald <http://github.com/zakmac>
JSBin: http://jsbin.com/foreda/edit?css
**/
.zero-places {
width: 1rem;
}
.one-place {
width: 1.2rem;
}
.two-places {
width: 1.23rem;
}
.three-places {
width: 1.235rem;
}
.four-places {
width: 1.2346rem;
}
.five-places {
width: 1.23457rem;
}
@charset "UTF-8";
/**
SASS NUMBER FUDGING FUNCTION
About: A SASS 3.2 compatible function that rounds a number to an accuracy of n decimal places
Author: Zak MacDonald <http://github.com/zakmac>
JSBin: http://jsbin.com/foreda/edit?css
**/
.zero-places {
width: #{fudge(1.234567)}rem;
}
.one-place {
width: #{fudge(1.234567, 1)}rem;
}
.two-places {
width: #{fudge(1.234567, 2)}rem;
}
.three-places {
width: #{fudge(1.234567, 3)}rem;
}
.four-places {
width: #{fudge(1.234567, 4)}rem;
}
.five-places {
width: #{fudge(1.234567, 5)}rem;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment