Based on "Get selected variation price in jQuery on Woocommerce Variable products" answer code, in my code bellow, I have a problem with the price calculation of a WooCommerce variable product.
The price gets multiplied with 10 or 1000, depending on the option selected on a dropdown, which is not supposed to happen and I don't know why it is happening.
Here is my code:
<script>
jQuery(function($) {
var jsonData = <?php echo json_encode($variations_data); ?>,
inputVID = 'input.variation_id';
$('input').change( function(){
if( '' != $(inputVID).val() ) {
var vid = $(inputVID).val(), // VARIATION ID
length = $('#cfwc-title-field').val(), // LENGTH
diameter = $('#diameter').val(), // DIAMETER
ene_enden = $('#id_dropdown_one_end').find('option:selected').attr("value_one_end"),
vprice = ''; // Initilizing
// Loop through variation IDs / Prices pairs
$.each( jsonData, function( index, price ) {
if( index == $(inputVID).val() ) {
vprice = price; // The right variation price
}
});
var rope_price = (length*vprice) + ene_enden;
if (rope_price != 0){
$('.price').html(rope_price+',-');
}
alert('variation Id: '+vid+' || Lengde: '+length+' || Diameter: '+diameter+' || Variantpris: '+vprice+ ' || Rope price: '+rope_price+' || ene_enden = '+ene_enden);
}
});
});
</script>
For some reason rope_price gets multiplied by 10 or concatenated with 0 when the option selected for 'I enden av tauet ' is 'Ingenting'(it's value is 0). When I change the option selected to any of the others rope_price gets multiplied with 1000 or concatenated with 00. I don't know why this is happening.
Any ideas?
Because you are concatenating strings. Is not the same 1 + 0 than "1" + "0", as you can check here:
console.log("1 + 0 =", 1 + 0);
console.log('"1" + "0" =', "1" + "0");
When you get a value from an HTML object, you receive it as a string. If you want to use it as a number you must convert it before. You can use either Number or parseFloat (even parseInt, but will remove decimals).
var oneNumber = 1;
var oneString = "1";
var oneConverted = Number(oneString);
console.log("typeof oneNumber:", typeof oneNumber);
console.log("typeof oneString:", typeof oneString);
console.log("typeof oneConverted:", typeof oneConverted);
console.log("oneNumber + oneNumber =", oneNumber + oneNumber);
console.log('oneString + oneString =', oneString + oneString);
console.log('oneConverted + oneConverted =', oneConverted + oneConverted);
The exact problem you are having is your ene_enden variable being a string in the line var rope_price = (length*vprice) + ene_enden;. When you multiply two strings, they are automatically converted to a number (your (length*vprice)), but when you concatenate that number to another string, they are converted automatically to a string again (your + ene_enden), so you must first convert ene_enden to a number, ot better convert all expected number variables to a number.
Related
The code is ideal for grades or GPA's, I am trying to display the average (GPAtotal / gpa.length) of the grades that is input by the user into an array. I was also asked to display a list of the outstanding GPA’s (Defined as GPA’s over 3.4)
I've tried:
Using parseInt() converting the input from string in an array to integers in an array.
Using gpa.reduce((a,b) => a + b, 0) / gpa.length, but the input are still string.
I've type of conversions to convert the strings into integers.
var gpa = [];
var theGPA = "";
while (theGPA != "XXX")
{
theGPA = prompt("Enter GPA or XXX to Stop");
if (theGPA != "XXX") {
gpa.push(theGPA);
}
}
document.getElementById('output').innerHTML += "Average: " + "???" + "<br/>";
document.getElementById('output').innerHTML += "Outstanding GPA: " + "???";
When attempting to display the average I would get the user imputed string as one solution, Example:
array: ["3.4", "4.0", "2.6"]
outputting: "Average: 4.04.32.6"
Code utilizing some of suggestions above
const gpa = ["3.4", "4.0", "2.6"];
const total = gpa.map(gpa => +gpa) // Map string to numeric (note the +)
.reduce((avg, gpa) => avg += gpa); // Sum the gpa's
const average = total / gpa.length; // Compute average
console.log(`Average: ${average.toFixed(2)}`); // toFixed converts to a string, don't use it if you want to do math with the result!
So two dropdowns and a few javascript functions to choose a price and set a country (which comes with a tax rate). Then display the price + tax rate = total to the user on the payment form.
If a price and a country(tax rate) are selected, the javascript and the sums work, thusly:
£49.99 + 10% VAT = £54.99
If a price but no country(tax rate) are selected, this happens:
Total: £49.99 + undefined% VAT = £NaN
And if neither a price or a country(tax rate) are selected, then we get:
£undefined + undefined% VAT = £NaN
So the question is: how do we deal with those ugly errors from javascript? What's the javascript way to deal with if/else for undefined and NaN?
Thanks.
UPDATE 2: the NaN check works, but where do I put the undefined check. Have added the TaxPrice function so you can see where it is coming from.
// First grab the tax rate from a drop down
function TaxPrice()
{
var taxprice=0;
var theForm = document.forms["payment-form"];
var selectedrate = theForm.elements["country_vat"];
taxprice = tax_rates[selectedrate.value];
return taxprice;
}
// Then calculate the total, including the NaN checks
function calculateTotal()
{
var TaxRate = TaxPrice() / 100;
var TotalPrice = PlanPrice() + (TaxRate * PlanPrice());
var TotalTax = (TaxRate * PlanPrice())
if(isNaN(TotalPrice)) {
// check NaN
TotalPrice = 0
}
if(isNaN(TotalTax)) {
// check NaN
TotalTax = 0
}
//display the price
var divobj = document.getElementById('p');
divobj.innerHTML = "£" + PlanPrice();
//display the tax rate
var divobj = document.getElementById('r');
divobj.innerHTML = "£" + TotalTax.toFixed(2) + " (" + TaxPrice() + "% VAT)";
//display the total
var divobj = document.getElementById('t');
divobj.innerHTML = "£" + TotalPrice.toFixed(2);
}
Check specifically for undefined with
if(typeof price === "undefined"){}
Check specifically for NaN with
if(isNaN(price)){}
Generally you can also simply do
if(price){}
Where the inside of the if statement will return false if price is NaN, undefined or null, but also when it is 0 or empty string, which you may not want so you'd need to specify it in the condition.
Specifically in your case, it would be good not to perform the calculations when either of its parts is not defined as the result will only create undefined or NaN values anyway:
function calculateTotal(){
//first check all you need for the calculation is defined
if (typeof TaxPrice() != 'undefined' && typeof PlanPrice() != 'undefined'){
//perform the calculation and output the result
}else{
//output an error message or a default ouput
}
}
Then you don't have to check for NaN's because those were caused by making arithmetics with undefined's.
Please covert value to a finite number, for example:
function toNumber(value) {
if(typeof value !== 'number') {
// covert type to number
// void 0, null, true, false, 'abc', [], {} => NaN
// [0] => 0
value = parseFloat(value)
}
if(isNaN(value)) {
// check NaN
value = 0
}
if(!isFinite(value)) {
// check Infinity and -Infinity
value = Number.MAX_SAFE_INTEGER * Math.sign(value)
}
return value
}
make a function similar to this
function get_value(input, default_value) {
return input === undefined || isNaN(input) ? default_value : input;
}
and then use it whenever you need to do calculations with a possible undefined value. Eg
var a = 10;
var sum = a + get_value(b, 0); // b is undefined and get_Value returns 0, sum is 10
var prod = a * get_value(b, 1); // b is undefined and get_Value returns 1, prod is 10
Use the isNaN() function to check if a variable is NaN.
e.g. see here: http://www.w3schools.com/jsref/jsref_isnan.asp
You could also track which vars were set in additional vars. ;)
If you want calculation to be done only when both of them are selected, then simply check for these errors in front of your code by:
if(typeof (your_price_variable) !== undefined && typeof (your_country_variable) !== undefined)
and make the function only run when this condition is met. Then the output won't be "NaN."
<script type="text/javascript">
//var EProductId = prompt('Please enter your product Id');
var EProductId = [];
EProductId[0] = prompt("New member name?");
//Product price, code, name, declare here
var ProductId = [];
ProductId[0] = 001;
var product = [];
product[0] = "tshirt";
var ProdPrice = [];
ProdPrice[0] = 299;
//Condition start here
if (ProductId[0] === EProductId[0]) {
// var EProductId2 = parseInt(prompt("Please enter a product", "")ProductId[0] + ' ' + product[0] + ' ' + ProdPrice[0]);
prompt(ProductId[0] + ' ' + product[0] + ' ' + ProdPrice[0]);
} else{
alert("You pressed Cancel or no value was entered!");
}
</script>
Why it is not entering in if condition. i am entering the value 001 after run a program but it alert the message is You pressed Cancel or no value was entered!
if (ProductId[0] == EProductId[0]) {}
Only use === when comparing types.
=== is only used for strict comparisons in javascript. For example: if('0' == 0) would return true as only values are compared here. However, === would check if they are of the same type (2 strings, 2 numbers, but not 1 of each). So, 0===0 returns true while 0==='0' returns false.
You should use == instead. Using == you can compare if values of different types are 'truthy' or 'falsy'. Example: 0 == 0 returns true as well as '0' == 0.
typeof(prompt()) returns string. You will have to convert it to an integer first using parseInt(string, radix). The 10 specifies base 10, the common numbering system used by people.
if (ProductId[0] === parseInt(EProductId[0],10))
I guess it returns "001" as a string, try this
if (ProductId[0] === +EProductId[0])
I have an array based on selected values from multiple select boxes:
Term 03 (-1000),1 (+1000),Price (+3000),1 (+1500),--,--,--,--,--,--,--,--,--,--,--,--,--,--,--,--,--,--
Comma-separated. As you can see, some values have text in parentheses. I need to take these values in parentheses and sum them, therefore the + and - characters should remain.
Values (+1000), (+3000), (-1000) represent changes of price: + indicates the product will be more expensive, - represents the product will be cheaper. The result of this should be a number that indicates change of the price - e.g. 1500 - the product will cost more than basic price, or e.g. -3000 - the product will be cheaper.
Thanks in advance.
Tom
You have comma-separated values, with numbers in them to extract. Start by splitting the input to an array, then for each item, extract the value using regexp for example:
/\(([+-])(\d+)\)/ //will search for a sign (+/-) and a number between parenthesis
applied to an item will result in an array having the sign in second position and the number in 3rd position
/\(([+-])(\d+)\)/.exec('Term 03 (-1000)') //--> ['Term 03 (-1000)', '-', '1000']
Use reduce to sum the all with consideration to the sign:
var changes = str.split(',').reduce(function(sum, item){
var matches = /\(([+-])(\d+)\)/.exec(item);
if(matches) {
return sum + (matches[1] === '-' ? -1 : 1) * parseInt(matches[2]);
} else {
return sum;
}
}, 0));
P.S.: If you have already an array, you can remove the .split(',') part.
If you are not great with regular expressions I've made a version that does not "use" them, this way it's more readable and easier to see what's going on and how it goes about doing it. Not to say you should not use regular expressions.
For this algorithm we are basically looking through each item, checking if they have valid parentheses, then if we have + we add the value inside the parentheses, otherwise if we have - we subtract (assuming those are the only two you can have):
for(items in array) {
var firstPar = array[items].indexOf("(");
var secondPar = array[items].indexOf(")");
// Check of the item has parentheses and are like this (...)
if( (firstPar > 0 && secondPar > 0) && (secondPar > firstPar) ) {
// Get the number from the string
var value = array[items].substring(firstPar+2, secondPar);
value = parseInt(value); // To Number
if( array[items].charAt(firstPar+1) == '+')
ProductPrice += value; // If "+" add
else
ProductPrice -= value;// If "-" subtract
}
}
Example Here
Maybe something like this:
var sum = 0;
csv.replace(/\([^)]+\)/gi, function (str) { sum += parseInt(str,10); return str; }
Didn't test code. Anyway idea is to use regex to loop all parenthesis and then inside replace function, convert matched string to integer and add it to sum.
I managed to get this to work with the rather cumbersome code below. It does work with both positive and negative integers.
var result = arr.map(function (el) {
if (el.indexOf('(') > -1 && el.indexOf(')') > -1) {
return Number(el.match(/\(([\+\- 0-9]*)\)/g)[0].replace(/[\(\) ]/g , ''));
}
}).filter(function (el) {
if (typeof el !== undefined) {
return el;
}
}).reduce(function (p, c) {
return p + c;
});
DEMO
Try
var arr = "Term 03 (-1000),1 (+1000),Price (+3000),1 (+1500),--,--,--,--,--,--,--,--,--,--,--,--,--,--,--,--,--,--".split(",")
, sum = 0;
arr.map(function(v, k) {
// cast `v` value as `Number` , e.g., `[-1000, 1000, 3000, 1500]`
var n = Number(v.replace(/\w+[^\(+\d+\)]|[\(|\)]/g, "")) || null;
// add `n` Number's at `sum` , e.g., `-1000 + 1000 + 3000 + 1500` = `4500`
sum += n
});
// console.log(sum); // `4500`
var arr = "Term 03 (-1000),1 (+1000),Price (+3000),1 (+1500),--,--,--,--,--,--,--,--,--,--,--,--,--,--,--,--,--,--".split(",")
, sum = 0;
arr.map(function(v, k) {
// cast `v` value as `Number` , e.g., `[-1000, 1000, 3000, 1500]`
var n = Number(v.replace(/\w+[^\(+\d+\)]|[\(|\)]/g, "")) || null;
// add `n` Number's at `sum` , e.g., `-1000 + 1000 + 3000 + 1500` = `4500`
sum += n
});
document.write(sum) // `4500`
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I'm currently producing a JavaScript driven mathematics package, which focuses on rounding to various significant figures (S.F.) but I've run into a problem that I'm struggling to solve.
More on this problem later, but first some background for you.
The program is designed to select a completely random number within a given range and then automatically work out that number's relevant significant figures; for example:
Random Number: 0.097027 S.Fs: 9, 7, 0, 2, 7
Here is a screenshot of what I have produced to give you a visual representation:
As you can see, once the user has selected their number, they are then given the opportunity to click on four separate 'SF' buttons to view their random number presented to 1, 2, 3 and 4 S.Fs respectively.
For each S.F (1-4) the random number is rounded down, rounded up and rounded off to X SF and a scale below gives the user a more visual presentation to show why the SF value has been chosen by the program.
I've already written the vast majority of the code for this and tested it and so far the numbers are coming out how I'm expecting them to. Well nearly...
In the example I've given (0.097027); as you can see on the image I've included, the data for 4 S.F is absolutely correct and outputted accurately.
When I click on to the 3 SF button, I'd expect to see the following:
Random Number: 0.097027 3 S.F Rounded Up/Down/Off: 0.0970
However, what I'm actually getting is:
Random Number: 0.097027 3 S.F Rounded Up/Down/Off: 0.097
The program hasn't displayed the additional zero. This is a perfect example of a number in my program ending in a zero and in this case the zero is really significant and must be displayed.
The data is usually correct but there appears to be an issue with outputting significant zeros at the right time. I've researched the toFixed(x) method and if I assign toFixed(4) I get the correct required output, but because my numbers are generated randomly each time, they can range from a length of 5 figures, e.g. 89.404 up to > 10, e.g. `0.000020615.
So it looks like the toFixed method needs to be flexible/dynamic, e.g. toFixed(n) with a function run beforehand to determine exactly how many trailing zeros are needed?
Here are some key excerpts from my current solution for your consideration:
function generateNum() {
do {
genNumber = Math.random() * Math.pow (10, randomRange(-5, 5));
//Round
genNumber = roundToNSF(genNumber, 5, 0);
// This number must contain >1 digit which is 1 to 9 inclusive otherwise we may have e.g. 100. Rounding 100
}
while (!countNonZero(genNumber) || genNumber < 1E-05 || genNumber == 0);
//Round
genNumber = roundToNSF(genNumber, 5, 0);
genNumber = String(genNumber);
genNumber = Number(genNumber);
}
//----------------------------------------------------------------------------
function randomRange(min, max) {
/**
* Returns a random integer between min (inclusive) and max (inclusive)
* Using Math.round() will give you a non-uniform distribution!
*/
return Math.floor(Math.random() * (max - min + 1)) + min;
}
//---------------------------------------------------------------------------
//Click SF3 Button to reveal the data
function showSF3() {
//Remove any CSS properties on the buttons from previous use
removeButtonCSS();
document.getElementById('SFRounded').style.display = "block";
document.getElementById('scale').style.display = "block";
document.getElementById("SF3").className = document.getElementById("SF3").className + "buttonClick"; // this removes the blue border class
//Clear text
deleteRounded();
deleteScale();
//Run calculation
calculateAnswer();
//alert(genNumber.toFixed(4));
for (i = 3; i < 4; i++)
{
//Add The new data
sfRoundedTextBlock = document.getElementById('SFRounded');
//alert(downArray[i].toFixed(4));
//Data output to HTML.
sfRoundedTextBlock.innerHTML = sfRoundedTextBlock.innerHTML + '<p><strong>Number: </strong></br>' + String(genNumber) +
'</br>' + '<strong>Rounded down to ' + i + ' SF:</br></strong>' + downArray[i] + '</br>' +
'<strong>Rounded up to ' + i + ' SF:</br></strong>' + upArray[i] + '</br><strong>Rounded off to ' + i + ' SF:</br></strong>'
+ roundedArray[i] + '</br>' + '(See the scale below for why we choose <strong>' + roundedArray[i] + '</strong> as the rounded off value.)</p>';
}
}
//----------------------------------------------------------------------
var roundedArray = [];
var upArray = [];
var downArray = [];
var temp;
function calculateAnswer() {
//Clear Arrays
roundedArray = [];
upArray = [];
downArray = [];
// Work out the answer:
for (i = 0; i < 4; i++) {
var nSF = i + 1;
// Round OFF ...
temp = roundToNSF(genNumber, nSF, 0);
// We actually have to do this twice ...
roundedArray[nSF] = roundToNSF(temp, nSF, 0);
// Round UP ...
upArray[nSF] = roundToNSF(genNumber, nSF, 1);
// Round DOWN ...
downArray[nSF] = roundToNSF(genNumber, nSF, -1);
// e.g. x = 0.0098 rounded to 1SF is 0.010 initially (take the log of 0.0098 and try it!).
};
};
//-------------------------------------------------------------------------
//Globals
var aNumber;
var digits;
var way;
function roundToNSF(aNumber, digits, way){
// Round a number to n significant figures (can use roundToNDP provided we know how many decimal places):
if (way == undefined) { way = 0; }; // default is round off
if (aNumber !=0) {
if (aNumber > 0)
{
z = log10(aNumber);
}
else
{
z = log10(-aNumber);
};
z = Math.floor(z);
var nDP = digits - z - 1; // Rounding to nDP decimal places is equivalent to rounding to digits significant figures ...
var roundedNumber = roundToNDP(aNumber, nDP, way);
}
else {
roundedNumber = aNumber; // Number is zero ...
};
return Number(roundedNumber);
};
//---------------------------------------------------------------------------------
Update:
I'm still continuing to try and find a solution for this problem and an approach I have recently taken is to convert my randomly generated number into a searchable string variable and then use the indexOf(".") command to find the position of the decimal point (dp).
Then I've searched through my number, starting from the position of the dp to find the first instance of a significant, non-zero number [1-9].
var genNumber = 0.097027;
var rString = String(genNumber);
var positionofDP = rString.indexOf(".");
var regexp = /[1-9]/;
var positionofNonZero = Number(rString.search(regexp, positionofDP)); // Output would be '5'
I have then been able to target my search further, to determine whether my first significant number has any 'problematic' zeros in the immediate digits after it.
If there are any, then I set a Boolean variable to 'true' and then in a separate function create further text strings of my rounded off/down/up numbers, so I can then physically choose to add a '0' on to the end of the existing numerical characters.
This approach does work for me in isolated cases, but with my random number length ranging from 5-12 digits long, it still isn't dealing with all scenarios.
Maybe I need to create a dynamic toFixed(i) function? Any ideas would be greatly welcomed.
Instead of playing with the fixed points on an Int, you could manage the string directly.
Here's a link to a little fiddle: http://jsfiddle.net/5rw5G/4/
This not intended to completely/accurately solve your problem, but might help you see another solution.
function getRoundedSFs(num, SFCount) {
// Match every "leading zeros" before and after the .
var matches = num.toString().match(/^-?(0+)\.(0*)/);
// starting with "0."
if (matches) {
var firstIndex = matches[0].length;
var prefix = matches[0];
sf = Number(num.toString().substring(firstIndex, firstIndex + SFCount + 1));
sf = Math.round(sf / 10);
sf = prefix + sf.toString();
return Number(sf).toFixed(matches[2].length+SFCount);
}
// starting with something else like -5.574487436097115
else {
matches = num.toString().match(/^(-?(\d+))\.(\d+)/);
var decimalShift = SFCount - matches[2].length;
var rounded = Math.round(num * Math.pow(10, decimalShift));
rounded /= Math.pow(10, decimalShift);
return rounded.toFixed(decimalShift);
}
}
I've gone away again and I think I have now finally managed solve my initial problem.
There was a degree of confusion on my part surrounding when to use toFixed and toPrecision. I had previously attempted to convert my rounded up, down and off numbers into strings and then subsequently search through each of these to find the decimal point (".") and then work out the amount of trailing numbers, in order to then generate the correct toFixed point.
However, this was very hit and miss, given that my random number could be up to 12 digits, so what I've now done is to properly utilise toPrecision instead. For each 'SF button' (1-4) I have used the corresponding toPrecision point, e.g for SF1:
sfRoundedTextBlock.innerHTML = sfRoundedTextBlock.innerHTML + '<p><strong>Number: </strong></br>' + String(genNumber) +
'</br>' + '<strong>Rounded down to ' + i + ' SF:</br></strong>' + downArray[i].toPrecision(1) + '</br>' +
'<strong>Rounded up to ' + i + ' SF:</br></strong>' + upArray[i].toPrecision(1) + '</br><strong>Rounded off to ' + i + ' SF:</br></strong>'
+ roundedArray[i].toPrecision(1) + '</br>' + '(See the scale below for why we choose <strong>' + roundedArray[i].toPrecision(1) + '</strong> as the rounded off value.)</p>';
//Add The new scale data (Rounded Down)
downTextBlock = document.getElementById('down');
document.getElementById("down").innerHTML = String(downArray[i].toPrecision(1));
//Add The new scale data (Rounded Up)
upTextBlock = document.getElementById('up');
document.getElementById("up").innerHTML = String(upArray[i].toPrecision(1));
This was now giving me accurate results on every occasion, but there was still one hurdle left to jump. Occasionally I would reach a random scenario where scientific notation would have to be included in my outputted answer, e.g. 21819 rounded down to 1 SF, would read out at 2e+4 instead of 20000.
To combat this I setup my up, down and rounded figures into searchable strings, and then looked through these to find any illegal/scientific characters [a-z]. If I found any, I executed a slightly different version of my output which made use of parseFloat, which stripped out the scientific notation and displayed the correct figures:
//Convert Up, Down and Rounded into Strings based on their precision
var upString = String(upArray[i].toPrecision(1));
var downString = String(downArray[i].toPrecision(1));
var roundedString = String(roundedArray[i].toPrecision(1));
//Set up a regexp to search for characters [a-z], i.e. non-numeric
var regexp = /[a-z]/g;
//Search the up, down and rounded strings for non-numeric characters
var upResult = upString.match(regexp);
var downResult = downString.match(regexp);
var roundedResult = roundedString.match(regexp);
//If any of these strings contain a letter (non-numeric) we need to add in parseFloat to strip away the scientific notation included.
var containsChar = false;
if (upResult != null || downResult != null || roundedResult != null)
{
containsChar = true;
//alert("There is SN included here");
}
//Add The new data
sfRoundedTextBlock = document.getElementById('SFRounded');
if (containsChar == true)
{
sfRoundedTextBlock.innerHTML = sfRoundedTextBlock.innerHTML + '<p><strong>Number: </strong></br>' + String(genNumber) +
'</br>' + '<strong>Rounded down to ' + i + ' SF:</br></strong>' + parseFloat(downArray[i].toPrecision(1)) + '</br>' +
'<strong>Rounded up to ' + i + ' SF:</br></strong>' + parseFloat(upArray[i].toPrecision(1)) + '</br><strong>Rounded off to ' + i + ' SF:</br></strong>'
+ parseFloat(roundedArray[i].toPrecision(1)) + '</br>' + '(See the scale below for why we choose <strong>' + parseFloat(roundedArray[i].toPrecision(1)) + '</strong> as the rounded off value.)</p>';
//Add The new scale data (Rounded Down)
downTextBlock = document.getElementById('down');
document.getElementById("down").innerHTML = String(parseFloat(downArray[i].toPrecision(1)));
//Add The new scale data (Rounded Up)
upTextBlock = document.getElementById('up');
document.getElementById("up").innerHTML = String(parseFloat(upArray[i].toPrecision(1)));
}
Having tested this extensively it seems to be working as hoped.