首先将默认精度设置为项目所需的最高精度。
然后,使用如下函数(基于Takeru Suzuki 的此函数)在单个属性级别自定义小数位数。
代码 :
@function decimal-round ($number, $digits: 0, $mode: round) {
$n: 1;
// $number must be a number
@if type-of($number) != number {
@warn '#{ $number } is not a number.';
@return $number;
}
// $digits must be a unitless number
@if type-of($digits) != number {
@warn '#{ $digits } is not a number.';
@return $number;
} @else if not unitless($digits) {
@warn '#{ $digits } has a unit.';
@return $number;
}
@if $digits > 0 {
@for $i from 1 through $digits {
$n: $n * 10;
}
}
@if $mode == round {
@return round($number * $n) / $n;
} @else if $mode == ceil {
@return ceil($number * $n) / $n;
} @else if $mode == floor {
@return floor($number * $n) / $n;
} @else {
@warn '#{ $mode } is undefined keyword.';
@return $number;
}
}
输出 :
decimal-round(0.333) => 0
decimal-round(0.333, 1) => 0.3
decimal-round(0.333, 2) => 0.33
decimal-round(0.666) => 1
decimal-round(0.666, 1) => 0.7
decimal-round(0.666, 2) => 0.67