Need javascript help - rounding up numbers and commas
Feb 17, 2020
Hello all! Can anyone please help me with the javascript prompt needed to fix my file? This is what I need a script for:
- Round up all numbers (I have several calculations in there). For example, whether the number that's calculated is 1.3 or 1.8, I need it to be rounded to 2 in the results layer. So far, I've only been figure out how to round up the 1.8 number, but not the 1.2 (that one always rounds to 1 with the script that I tried).
- Put commas in the numbers on the results layer if the result is anything above 999.
I've tried Russell's suggestion from this post for #1. It does seem to round up if the number is .5 or below, it rounds down instead.
I've also tried this suggestion for #2, but I couldn't get it to work. Maybe I missed something?
Thank you everyone!
6 Replies
Hi Matthew! Thanks for your response. This one also appears to round "down". For example, if the number is 1.3, it rounds down to 1 rather than to 2. Am I missing something?
A friend actually just helped me out for #1 in case anyone ever finds this:
var player = GetPlayer();
var num = player.GetVar("VariableName");
num = Math.ceil(num);
player.SetVar("VariableName",num);
Hello Alina,
Unfortunately you cannot use comma's in a number type field.
For this to work, the variable will have to be Text Type.
Try this javascript. It rounds the number up and puts in comma's.
var player = GetPlayer();
var num = parseFloat(player.GetVar("TextEntry"));
num = Math.ceil(num);
num = num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
player.SetVar("TextEntry",num);
Thanks, Russell. It's ok if it won't type it in the field with commas, but I'd like it to show in the results layer with commas. I wasn't able to get the code to work for the commas. If I typed in $100,000 for the desired revenue, it changed it to $1 in the results. I think it's because of this section of the code: "/g, '$1,');" on the second to last line.
I tried to change that $1 to other numbers, but still couldn't get it to work.
The math.ceil definitely works for my rounding that I wanted.
Try this example project.
Thank you!
This discussion is closed. You can start a new discussion or contact Articulate Support.