Rounding numbers in Sass and adjusting the amount of decimals

旧街凉风 提交于 2019-11-28 10:18:01

From the SASS change logs:

The numeric precision of numbers in Sass can now be set using the --precision option to the command line. Additionally, the default number of digits of precision in Sass output can now be changed by setting Sass::Script::Number.precision to an integer (defaults to 3). Since this value can now be changed, the PRECISION constant in Sass::Script::Number has been deprecated. In the unlikely event that you were using it in your code, you should now use Sass::Script::Number.precision_factor instead.

This was added in SASS 3.1.8.

A quick option without any extra functions would be to multiply the number by 1000, then round it, then divide by 1000.

round($percent * 1000) / 1000;

You could use the following function, which is a slight improvement of the function created by 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;
    }
}

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

You could also do the following:

@function ceilHundredths($numbers) {
    $numbers: $numbers * 10000;

    @if ($numbers < 1) {
        $numbers: $numbers - 1;

    } @else {
        $numbers: $numbers + 1;
    }

    @return round($numbers)/ 100#{"%"};

}

.test--regular {
    margin-left: percentage( -1 / 3 );
}

.test {
    margin-left: ceilHundredths( -1 / 3 );
}

.test--regular--2 {
    margin-left: percentage( 1 / 3 );
}

.test--2 {
    margin-left: ceilHundredths( 1 / 3 );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!