Sass and rounding down numbers. Can this be configured?

后端 未结 3 1480
野性不改
野性不改 2020-12-03 18:15

Is there any way for me to modify the way that Sass will handle decimal places? I saw a few people saying that Sass will dynamically do the (target/parent)*100 calculation n

3条回答
  •  渐次进展
    2020-12-03 18:53

    First set your default precision to the highest precision you're going to need in your project.

    Then, use a function like the one below (which is based on this function by Takeru Suzuki) to customize the number of decimals at the level of individual properties.

    Code :

    @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;
        }
    }
    

    Output :

    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
    

提交回复
热议问题