Skip to content
Merged
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
5 changes: 4 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ function reduceCSSCalc(value, decimalPrecision) {

if (unit === "%") {
// Convert percentages to numbers, to handle expressions like: 50% * 50% (will become: 25%):
// console.log(expression)
expression = expression.replace(/\b[0-9\.]+%/g, function(percent) {
return parseFloat(percent.slice(0, -1)) * 0.01
})
Expand All @@ -84,7 +85,9 @@ function reduceCSSCalc(value, decimalPrecision) {

// adjust rounding shit
// (0.1 * 0.2 === 0.020000000000000004)
result = Math.round(result * decimalPrecision) / decimalPrecision
if (functionIdentifier.length || unit === "%") {
result = Math.round(result * decimalPrecision) / decimalPrecision
}

// We don't need units for zero values...
if (result !== 0) {
Expand Down
4 changes: 3 additions & 1 deletion test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ test("reduce complexe css calc()", function(t) {
t.equal(reduceCSSCalc("calc(((1rem * 0.75) * 1.5) - 1px)"), "calc(1.125rem - 1px)", "multiple units with implicit calc")
t.equal(reduceCSSCalc("calc(-1px + (1.5 * (1rem * 0.75)))"), "calc(-1px + 1.125rem)", "multiple units with implicit calc, reverse order")
t.equal(reduceCSSCalc("calc(2rem * (2 * (2 + 3)) + 4 + (5/2))"), "26.5rem", "complex math formula works correctly")

t.equal(reduceCSSCalc("calc((4 * 2) + 4.2 + 1 + (2rem * .4) + (2px * .4))"), "calc(8 + 4.2 + 1 + 0.8rem + 0.8px)", "handle long formula")
t.equal(reduceCSSCalc("calc((2 * 100) / 12)"), reduceCSSCalc("calc((100 / 12) * 2)"), "indentical, wrong rounded")
t.equal(reduceCSSCalc("calc((2 * 100) / 12)", 3), "16.667", "indentical rounded with options")
t.equal(reduceCSSCalc("calc((100 / 12) * 2)", 3), "16.667", "indentical rounded with options")
t.end()
})

Expand Down