JavaScript incrementing by 0.5 - how? - javascript

I have a problem incrementing a number by 0.5. I've used "+=" operator but instead of incrementing my number, this adds "0.5" value in the end of number. The example is this:
<script>
function setTempUp(){
var value = document.getElementById("targetTemp").firstChild.data;
var newvalue = value.replace("°","");
var num = new Number(newvalue);
var num = newvalue += 0.5;
var newtemp = newvalue + '°';
document.getElementById("targetTemp").innerHTML = newtemp;
var cover = document.getElementById('tempChange').clientHeight;
var coverInt = parseInt(cover, 10);
var coverNew = cover - 11;
document.getElementById('tempChange').setAttribute("style","height:" + coverNew + "px");
}
</script>
I'm also "attaching" "°" to my "newTemp", because I have temperature example. Is this a problem?
So, my number is 24 for example - when executed I get "240.5" :(

newvalue is a string. Use += on your num directly:
num += 0.5;

You are casting it to a number, but still call the string variable in the following code:
var num = new Number(newvalue);
var num = newvalue += 0.5;
var newtemp = newvalue + '°';
I think that what you meant to do was
var num = new Number(newvalue);
num = num += 0.5;
var newtemp = num + '°';
But whichever it is, you should keep a numeric variable out of the function, and increment that, instead of loading the temperature that you posted on the screen from the last run, and then do it again over and over.

newValue is a string - returned by value.replace("°","");
Instead of
var num = newvalue += 0.5;
Use
newValue = parseInt(newvalue, 10) + 0.5;
(Since you're not using num anywhere else, you don't need to assign it any result.)

Related

How do I take a variables prior value and subtract it from the final value if the total value of the variable cannot exceed a certain amount?

example:
var num = 20;
var sub = 6;
var add = 10;
num = num - sub;
num = num + add;
if (num>20){
num = 20;}
console.log("X was added to var num");
How can I get the console log to say that var num really only had 6 added to it before it hit it's max value?
Your question isn't very clear. Do you need to keep a log of what num is?
I would reccomend an array for that:
let log = [];
Then before you change num:
log.push(num);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
If you just want the console to display the value of a variable there's several ways:
console.log(add, " was added to var num");
console.log(add + " was added to var num");
console.log(`${add} X was added to var num`);
https://developer.mozilla.org/en-US/docs/Web/API/Console/log
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

How can I add up two or more array elements (numbers)

I want to add up all of the element from var string to each other.
I did try this but now I want to do this for each element.
var operator = document.getElementById("operation").value;
var number = document.getElementById("numbers").value;
var string = number.split(",");
var number1 = string[0];
var number2 = string[1];
var sum = number1 + number2;
document.getElementById("result").innerHTML = parseInt(sum);
Any help is welcome!
Use reduce() and don't forget to cast your string into int:
var number = "1,2,3,4,5"
var sum = number.split(",").reduce(function (total, num) {
return total + parseInt(num);
}, 0);
You can do R. Saban's way and there are also other ways as well. For example try this:
var start = 0; // Using this to add each element in the array starting from 0, look below
var number = document.getElementById("numbers").value;
var string = number.split(",");
string.forEach(function (num) {
start += parseInt(num);
});
// variable "start" will hold the end result

Compound assignment in Javascript resulting in NaN

I'm trying to get compound assignment working inside a loop in Javascript but it's throwing NaN at me and I don't know why as I'm still fairly new to Javascript. I am essentially trying to translate this into a jQuery-Validation custom method: https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php
Here's what I have so far
// Taken from https://github.com/pfwd/NHSNumber-Validation
var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
var currentSum, currentNumber, currentMultiplier = 0;
//Get submitted NHS Number and remove whitespace
var givenNumber = value.replace(/\s+/g, '');
// Get length
var numberLength = givenNumber.length;
console.debug(givenNumber);
console.debug(numberLength);
// Number must be 10 digits in length
if (numberLength !== 10) {
return false;
}
// Check number
var checkNumber = value.substring(9);
console.debug(checkNumber);
// Loop over each number in the string and calculate the current sum
for (var i = 0; i <= 8; i++) {
var minus = i-1;
var plus = i+1;
currentNumber = value.charAt(i);
currentMultiplier = multipliers[plus];
currentSum += (currentNumber * currentMultiplier);
console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
}
var remainder = currentSum % 11;
var total = 11 - remainder;
console.debug(currentSum);
I don't know if the minus and plus vars are necessary but they're something I tried while trying to fix the NaN issue. A typical console debug line looks like this:
i is 0 & current Num: 1 plus current multi: 10 plus NaN
I've also tried this with the same NaN result:
currentSum = currentSum + (currentNumber * currentMultiplier);
var currentSum, currentNumber, currentMultiplier = 0;
is incorrect, and only initalizes currentMultiplier.
It should be
var currentSum, currentNumber, currentMultiplier;
currentSum = currentNumber = currentMultiplier = 0;
demo : http://jsfiddle.net/46dD5/

Javascript Showing even numbers only

I've got this project where I have to generate random mathematics sums...
They are all 'divide by' sums, so I want to make all numbers even.
Can anyone help me with this? just ask if I'm not clear enough =)
<script>
$(function() {
var number = document.getElementById("breuken"),
i = 1;
for (; i <= 10; i++) {
var sRandom = Math.floor(Math.random()*10 + 1),
fRandom = Math.floor(sRandom + Math.random()*(20-sRandom )),
calc = Math.abs(fRandom / sRandom),
textInput = document.createElement('input'),
span = document.createElement('span'),
p = document.createElement('p');
textInput._calc = calc;
textInput.onchange = (function(p) {
return function(ev) {
var self = ev.target;
if (self.value == self._calc) {
p.style.color = 'green';
};
};
})(p);
span.innerHTML = fRandom + " : " + sRandom + " = ";
p.appendChild(span);
p.appendChild(textInput);
number.appendChild(p);
};
});
</script>
To get an even random number just:
halve you range and multiply by 2
var range = 100;
var number = Math.floor( Math.random() * range / 2 ) * 2;
or keep getting random numbers until you get an even one
var number;
do {
number = Math.floor(Math.random()*10 + 1)
} while( number % 2 == 1 );
Get a random integer over 1/2 the range and double it.

Attempting to output value of math formula applied to array is failing [Jquery]

I'm attempting to get a coefficient of variation calculator working with jQuery, and can't seem to get it to output a correct answer.
My current code:
var fields = $('#cvform').serializeArray();
var num = 0;
var mean = 0;
var m2 = 0;
var total = 0;
jQuery.each(fields, function(i, field){
if (field.value > 0) {
num++;
var delta=(field.value-mean);
var mean=(mean+delta/num);
var m2=(m2+delta*(field.value-mean));
var total=(total+field.value);
};
});
var cov=(((Math.sqrt(m2/(num-1)))/(total/num))*100);
$("<span>Coefficient of Variation: " + delta + m2 + num + total + cov + "</span>").appendTo('#cvdisplay');
When I attempt to output the values after, it tells me that delta is undefined, mean m2 and total are = 0, and num is output correctly. Cov is simply output as NaN. The array of #cvform is simply text inputs that can only be numbers. Can anyone point me in the right direction of getting this to function?
You declare delta within a function, so it isn't visible outside the for loop. Move its declaration out of the each block and it will be found.
var fields = $('#cvform').serializeArray();
var num = 0,
mean = 0,
m2 = 0,
total = 0,
delta = 0;
jQuery.each(fields, function(i, field){
if (field.value > 0) {
num++;
delta=(field.value-mean);
mean=(mean+delta/num);
m2=(m2+delta*(field.value-mean));
total=(total+field.value);
};
});
var cov=(((Math.sqrt(m2/(num-1)))/(total/num))*100);
$("<span>Coefficient of Variation: " + (delta + m2 + num + total + cov) + "</span>").appendTo('#cvdisplay');

Categories

Resources