Skip to content

Instantly share code, notes, and snippets.

@jerrysdesign
Forked from terkel/_decimal.scss
Created November 5, 2015 06:30
Show Gist options
  • Select an option

  • Save jerrysdesign/da4c82a8b99a77d21525 to your computer and use it in GitHub Desktop.

Select an option

Save jerrysdesign/da4c82a8b99a77d21525 to your computer and use it in GitHub Desktop.
Rounding decimals in Sass
// Round
@function round-decimal ($number, $digits: 0) {
@return to-fixed($number, $digits);
}
// round-decimal(0.333) => 0
// round-decimal(0.333, 1) => 0.3
// round-decimal(0.333, 2) => 0.33
// round-decimal(0.666) => 1
// round-decimal(0.666, 1) => 0.7
// round-decimal(0.666, 2) => 0.67
// Ceil
@function ceil-decimal ($number, $digits: 0) {
@return to-fixed($number, $digits, ceil);
}
// ceil-decimal(0.333) => 1
// ceil-decimal(0.333, 1) => 0.4
// ceil-decimal(0.333, 2) => 0.34
// ceil-decimal(0.666) => 1
// ceil-decimal(0.666, 1) => 0.7
// ceil-decimal(0.666, 2) => 0.67
// Floor
@function floor-decimal ($number, $digits: 0) {
@return to-fixed($number, $digits, floor);
}
// floor-decimal(0.333) => 0
// floor-decimal(0.333, 1) => 0.3
// floor-decimal(0.333, 2) => 0.33
// floor-decimal(0.666) => 0
// floor-decimal(0.666, 1) => 0.6
// floor-decimal(0.666, 2) => 0.66
@function to-fixed ($number, $digits: 0, $round: round) {
$n: 1;
@if type-of($digits) == number {
@for $i from 1 through $digits {
$n: $n * 10;
}
}
@if $round == ceil {
@return ceil($number * $n) / $n;
} @else if $round == floor {
@return floor($number * $n) / $n;
} @else {
@return round($number * $n) / $n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment