Reputation: 689
I`m trying to get percentage in lesscss file with 2 digits accuracy. In lesscss file
@w: round(((100-((12-5)*3.8))/(12/5))*100);
width: percentage(@w/10000);
Compiles to width: 30.580000000000002%; What I`m doing wrong?
My logic is very simple:
Step 1: Get the "not right" digit 30.580000000000002
Step 2: 30.580000000000002*100 = 3058.0000000000002
Step 3: round(3058.0000000000002) = 3058
Step 4: 3058/10000 = 0.3058
Step 5: percentage(0.3058) = 30.58
Upvotes: 2
Views: 2093
Reputation: 35826
Your question can be important when trying to minimize data traffic. These days, it does not make sense to send CSS percentages over the wire with more than one or two figures in the mantissa.
Given the following LESS input:
w: 100 %;
w: round(512 * 1%, 2);
w: 2.0 / 3.0 * 100 * 1%;
w: round(2.0 / 3.0 * 100 * 1%, 2);
w: round(0.19%, 2);
w: round(0.19%, 1);
w: round(10000%, 1);
w: round(10000, 1);
and corresponding output:
w: 100 %;
w: 512%;
w: 66.66666666666666%;
w: 66.67%;
w: 0.19%;
w: 0.2%;
w: 10000%;
w: 10000;
we see that round(percentage, 2)
non-destructively achieves what we want.
Upvotes: 1
Reputation: 14980
You are not considering that floating-point computation is done in binary, where there is no exact representation of 1/10000. Therefore:
/* 30.580000000000002 */
console.log(Math.round(((100 - ((12 - 5) * 3.8))/(12 / 5)) * 100) / 10000 * 100);
(It does not matter if LESS uses an ECMAScript implementation like JavaScript, as long as computation is based on IEEE-754 double-precision floating-point numbers.)
However, you should not bother about that.
width: 30.580000000000002%;
Upvotes: 2
Reputation: 38253
You need to wrap your round()
method around the percentage()
method, like so:
@w: round(((100-((12-5)*3.8))/(12/5))*100);
width: round(percentage(@w/10000));
Upvotes: 1