Sass and rounding down numbers. Can this be configured?

≡放荡痞女 提交于 2019-11-27 15:35:46
Alex.Designworks

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

Torkil Johnsen

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.

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!