Forum Discussion

Doug1234's avatar
Doug1234
Community Member
4 hours ago

Calculating trig functions to more than two decimal places in javascript

Hi all,

 

I'm trying to boost my game in terms of SL360 development and I'm creating a simple function where the user turns a dial to change an angle, and the sine, cosine and tangent of the angle is automatically calculated.

 

I've created the tool fine and it wors as it should; however, it only calculates the trig functions to two decimal places and i'd like it to calculate them to four decimal places. 

 

Here is the javascript I created that does this (notes were put in for my benefit): 

let player = GetPlayer();

let degrees = player.GetVar("Angle"); //retrieves the value of the angle from SL360
let radians = degrees * (Math.PI/180); //converts to radians to calculate the sine of the variable "Angle"
let sinAngle = Math.sin(radians);//calculates the sine of "Angle"
let cosAngle = Math.cos(radians); //calculates the cosine of "Angle"
let tanAngle = Math.tan(radians); //calculates the tangent of "Angle"


player.SetVar("Sine",sinAngle); //outputs the value of sinAngle to the SL360 variable of "Sine"
player.SetVar("Cosine",cosAngle); //outputs the value of cosAngle to the SL360 variable of "Cosine"
player.SetVar("Tangent",tanAngle);//outputs the value of tanAngle to the SL360 variable of "Tangent"

 

It works fine, but I just need to know how to calculate the values to more than two decimal places. i've tried using .toFixed(), but haven't had any luck with it. 

 

any help would be appreciated. 

 

Regards,

 

Doug

  • The problem isn't that the functions are not calculated to a higher precision, but that Storyline only displays 2 decimals in its numbers. You can output your JavaScript calculations to the developer console (F12) to see the larger value. For example:

    console.log(Math.tan(radians));

    If you want the longer value in Storyline, then you can use a text variable to retain additional decimal places.  The toFixed() function also outputs a string rather than a number, so it's better suited to return to a SL text variable as well.

    As you probably know, you can't use text variables in SL for calculations, but you probably aren't doing those inside SL anyway. If you pass any text values to JavaScript for numeric calculations, you need to make sure they are converted to numbers before using them. For example, let's say you use

    GetPlayer().GetVar("myValue");

    to retrieve the text value "4.53453287" from SL. To ensure this is a value and not a string in JavaScript, you can use a statement like

    Number(GetPlayer().GetVar("myValue") || 0);

    which returns either the numeric conversion of the string, or 0 if the string doesn't represent a number. Otherwise, you risk creating concatenated strings when doing things like addition in JavaScript.