SL 360 calculations & JS formatting

Nov 06, 2019

A while back, I posted about configuring calculations in SL, and was able to do this using variables etc. Since then, I've managed to find JS code that does the same thing. The trouble is now, I need to be able to format the result so that if 10000 is the output, then this needs commas i.e. 10,000.

I have 4 variables in SL:

FP_Amt
FP_Tax
FP_Net
FP_Week

The calculations are as follows:

Income (typed by user)
Tax * 30% of income
Net is income - tax
Week is Net / 52

The working JS code:

var player = GetPlayer();
var FP_Amt_JS = player.GetVar("FP_Amt");
var FP_Tax_JS = FP_Amt_JS * 0.30;
var FP_Net_JS = FP_Amt_JS - FP_Tax_JS;
var FP_Week_JS = FP_Net_JS / 52;
player.SetVar("FP_Tax",FP_Tax_JS);
player.SetVar("FP_Net",FP_Net_JS);
player.SetVar("FP_Week",FP_Week_JS);

I've  been searching high and low for code that will help with formatting the 3 output variables. I'm not experienced with JS, and seem to be just getting lost. I cannot seem to find anything that details what's needed. It's frustrating that there isn't an option built-in that allows for formatting of numbers like this in SL, and seems to be quite complicated in JS too.

Any help will be greatly appreciated.

Thank you :)

5 Replies
David Schwartz

Hi Blue,

Here's a way. I don't know JS too well, so cobbled together some things, among them to round each amount to avoid having decimal places in your numbers.

I added three text variables, as you need them to contain the values with commas.

https://360.articulate.com/review/content/d33a8dd2-c18a-4786-b4b9-6af162138ca6/review

The JS is here:

var player = GetPlayer();

function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

var FP_Amt_JS = player.GetVar("FP_Amt");
var FP_Tax_JS = Math.round(FP_Amt_JS * 0.30);
var FP_Net_JS = Math.round(FP_Amt_JS - FP_Tax_JS);
var FP_Week_JS = Math.round(FP_Net_JS / 52);

player.SetVar("Tax_text",formatNumber(FP_Tax_JS));
player.SetVar("Net_text",formatNumber(FP_Net_JS));
player.SetVar("Week_text",formatNumber(FP_Week_JS));

 

 

Blue Kearsley

This is the code I used to calculate the values as needed, and split with commas, and also only have 2 decimal places. Thank you for your help.

var player = GetPlayer();
function Commas(x) {
var parts = x.toFixed(2).split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
var FP_Amt_JS = player.GetVar("FP_Amt");
var FP_Tax_JS = FP_Amt_JS * 0.30;
var FP_Net_JS = FP_Amt_JS - FP_Tax_JS;
var FP_Week_JS = FP_Net_JS / 52;
player.SetVar("Tax_text",Commas(FP_Tax_JS));
player.SetVar("Net_text",Commas(FP_Net_JS));
player.SetVar("Week_text",Commas(FP_Week_JS));

This discussion is closed. You can start a new discussion or contact Articulate Support.