Anshul
Anshul

Reputation: 9480

Decimal rounding issue while calculating angle of triangle

I am creating three angles. These angles creates a triangle.I want to show calculated angle in my canvas, for that I am calculating angle and rounding off for showing.While calculating the angle's , I am rounding off the decimal digits using Math.round().

So if I got 65.25, 70.36, 44.39 degree as value of three angles and after rounding off it will be 65,70,44,which become 179 degree instead of 180 degree(One degree is missing here).How can I solve this problem ? Here are some images for reference

enter image description here

Upvotes: 0

Views: 287

Answers (1)

andand
andand

Reputation: 17497

One approach is to compute the third angle (rounded) based upon the other two, rather than simply rounding them all as you have done. For instance:

var th0 = 65.25;
var th1 = 70.36;
var th2 = 44.39;

var th0r = Math.round(th0);
var th1r = Math.round(th1);
var th2r = 180.0 - th0r - th1r;

This will force th0r + th1r + th2r to always sum to 180. You can become a little more sophisticated by picking the best angle to compute from the other two, but this will probably suffice for most applications.

Upvotes: 2

Related Questions