Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/lib/serialize.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
* @property {string} [calcName] Wrapper name to use when `calc()` is needed. Default `'calc'`.
*/

const NOISE_FLOOR = 1e-12;

/**
* @param {number} v
* @param {number | false} prec
Expand All @@ -25,7 +27,11 @@ function round(v, prec) {
return v;
}
const m = Math.pow(10, prec);
return Math.round(v * m) / m;
const rounded = Math.round(v * m) / m;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should be some comment about explaining why the code is doing this or nobody will understand it in the future.

if (rounded === 0 && Math.abs(v) > NOISE_FLOOR) {
return v < 0 ? -1 / m : 1 / m;
}
return rounded;
}

// §10.13 / §10.7.2: Infinity/NaN serialize as canonical keywords.
Expand Down
20 changes: 20 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,26 @@ test(
testValue('calc(5/1000000)', '0.000005', { precision: 6 })
);

test(
'should not round a non-zero value down to zero',
testValue('calc(1/1000000)', '0.00001')

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why does dividing 1 by one million give 1e-06 instead of 1e-05? I guess it's related to the precision being 5 decimal digits, but I would appreciate some explanation or a link to the spec.

);

test(
'should not round a non-zero dimension down to zero',
testValue('calc(1px/1000000)', '0.00001px')
);

test(
'should not round a non-zero negative value down to zero',
testValue('calc(-1/1000000)', '-0.00001')
);

test(
'should keep rounding float noise to zero',
testValue('calc(0.1px + 0.2px - 0.3px)', '0px')
);

test(
'should reduce browser-prefixed calc (1)',
testValue('-webkit-calc(1px + 1px)', '2px')
Expand Down