Sass and rounding down numbers. Can this be configured?

后端 未结 3 1462
野性不改
野性不改 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
    
    0 讨论(0)
  • 2020-12-03 19:04

    It can also be configured using --precision in the commandline, see SASS Changelog, version 3.1.8.

    Should also add that if you want to edit @precision in numbers.rb directly, you can find numbers.rb (at least on OS X), here:

    /usr/lib/ruby/user-gems/1.8/gems/sass-3.1.10/lib/sass/script
    

    1.8 and 3.1.10 should of course be replaced with your (preferably the latest) version numbers.

    0 讨论(0)
  • 2020-12-03 19:07

    If you are using Compass, you can easily specify the precision in your project file (config.rb) without hacking the core:

    Sass::Script::Number.precision = 8
    

    For more information see Sass documentation

    0 讨论(0)
提交回复
热议问题