Skip to content

Commit 774f3f0

Browse files
committed
Handle rounding issues
1 parent 96838b6 commit 774f3f0

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ var reduceFunctionCall = require("reduce-function-call")
88
* Constantes
99
*/
1010
var MAX_STACK = 100 // should be enough for a single calc()...
11+
var DECIMAL_PRECISION = 10000 // 5 decimals
1112

1213
/**
1314
* Global variables
@@ -97,6 +98,10 @@ function evaluateExpression (expression, functionIdentifier, call) {
9798
// Transform back to a percentage result:
9899
if (unit === "%") {
99100
result *= 100
101+
102+
// adjust rounding shit
103+
// (0.1 * 0.2 === 0.020000000000000004)
104+
result = Math.round(result * DECIMAL_PRECISION) / DECIMAL_PRECISION
100105
}
101106

102107
// We don't need units for zero values...

test/index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,11 @@ test("reduce prefixed css calc()", function(t) {
7272
t.end()
7373
})
7474

75+
test("handle rounding issues", function(t) {
76+
t.equal(reduceCSSCalc("calc(10% * 20%)"), "2%", "should round percentage")
77+
t.end()
78+
})
79+
7580
test("ignore unrecognized values", function(t) {
7681
t.equal(reduceCSSCalc("calc((4px * 2) + 4.2 + a1 + (2rem * .4))"), "calc(8px + 4.2 + a1 + 0.8rem)", "ignore when eval fail")
7782
t.end()

0 commit comments

Comments
 (0)