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
Javascript's toLocaleString function supports this functionality. For example,
(1234567.0987).toLocaleString();
You may need to change the variable types to string to receive the converted type as it's a text string, not a number
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));
Thanks Brian, and David. That works lovely, I'm taking out the rounding as I need the decimal place, but that is just what I needed, thank you SO much!
I'll repost the JS code once I've re-added the decimal to 2 points.
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.
Very cool! Thanks for sharing that!
This discussion is closed. You can start a new discussion or contact Articulate Support.