cuixiping
cuixiping

Reputation: 25371

SVG polyline/polygon's points dom value is different from points attribute value

See this svg code

<polyline id="poly" points="163.2 100 163.2 200"
     stroke-width="1" fill="none" stroke="red"></polyline>

and this javascript code

var poly = document.getElementById('poly');
console.log(poly.points.getItem(0).x);

will get 163.1999969482422. not the expected 163.2

and (163.2 == 163.1999969482422) is false in javascript.

I tested in chrome and firefox.

Is this a bug or I must use poly.getAttribute('points') and parse the attribute value string to array?

Upvotes: 2

Views: 89

Answers (1)

Robert Longson
Robert Longson

Reputation: 123985

To improve speed and performance, most UAs encode polyline points as IEEE-754 format floats. 163.2 cannot be exactly represented in binary in the 32 bit IEEE-754 format. The nearest 32 bit IEEE-754 value to 163.2 is 163.1999969482422 as you've discovered by experimentation. And that's how the value is stored internally.

javascript however stores numbers in 64 bit IEEE-754 binary which allows greater precision so the nearest 32 bit value does not match the nearest 64 bit value exactly.

Upvotes: 1

Related Questions