Javascript. Math.sqrt giving NaN to a positive number? - javascript

I currently have a script that takes numbers from a text area and does all sorts of calculations with them. I am having trouble with my standard deviation function because it will not output the value even though it's type is number, and it is positive (.56).
When I run this code
var variance = findVariance(array);
variance = parseFloat(variance);
alert(typeof variance);
the result is
number
And the value is .56 (which I know because when I don't use parseFloat it returns .56 as a string). So I am baffled when I run this code
alert("variance " + variance);
alert("sd" + Math.sqrt(variance));
and both alerts return
NaN
This is the code that creates the textarea, calls the function processData( which gathers the input from myTextArea into an array and then calls the function findStandardDeviation) I can post the variance function as well if you'd like.
<textarea id="myTextArea" rows = "7" cols = "50"></textarea><br>
<button onclick="processData()">Done</button>
<p id = "sd"></p>
<script type = "text/javascript">
var standard_deviation = 0;
var sdOutput = document.getElementById('sd');
function processData()
{
var arrayOfLines = document.getElementById('myTextArea').value.split('\n');
findStandardDeviation(arrayOfLines);
}
This is the most reducible form of my script I could manage:
var mean = 0;
var median = 0;
var count = length;
var mode = 0;
var variance = 0;
var standard_deviation = 0;
var meanOutput = document.getElementById('mean');
var countOutput = document.getElementById('count');
var sumOutput = document.getElementById('sum');
var varianceOutput = document.getElementById('variance');
var sdOutput = document.getElementById('sd');
function processData() {
var arrayOfLines = document.getElementById('myTextArea').value.split('\n');
var sum = findSum(arrayOfLines);
findMeanOutput(arrayOfLines, sum);
findVariance(arrayOfLines);
findStandardDeviation(arrayOfLines);
}
function findSum(array) {
var count = array.length;
var sum = 0;
for (var a = 0; a < array.length; a++) {
sum += parseInt(array[a]);
}
countOutput.innerHTML = "Count: " + array.length;
sumOutput.innerHTML = "Sum: " + JSON.stringify(sum);
sum = parseInt(sum);
return sum;
}
function findMean(array) //Used for finding mean and then returning it
{
var sum = 0;
for (var a = 0; a < array.length; a++) {
sum += parseFloat(array[a]);
}
mean = sum / array.length;
return mean;
}
function findMeanOutput(array, sum) //finds mean and then establishes it as the mean for users input
{
mean = sum / array.length;
meanOutput.innerHTML = "Mean: " + mean;
}
function findVariance(array) {
var mean = findMean(array);
var variance = "Variance: " + findMean(array.map(function(num) {
return Math.pow(num - mean, 2);
})).toFixed(2);
varianceOutput.innerHTML = "Variance: " + variance;
return variance;
}
function findStandardDeviation(array) {
var variance = findVariance(array);
variance = parseFloat(variance);
alert(typeof variance);
alert("variance " + variance);
alert("sd" + Math.sqrt(variance));
sdOutput.innerHTML = "Standard Deviation: " + Math.sqrt(variance).toFixed(2);
}
<html>
<head>
</head>
<body>
<p> Please enter a series of numbers, each separated by a new line.<br>
<p>
<textarea id="myTextArea" rows="7" cols="50"></textarea><br>
<button onclick="processData()">Done</button>
<p id="mean"></p>
<p id="count"></p>
<p id="sum"></p>
<p id="variance"></p>
<p id="sd"></p>
</body>
</html>

.56 is not an integer, so you shouldn’t use parseInt. parseFloat is the function you’re looking for. Or much simpler: Number.

Try For this:
in your case .56 is float, so use parseFloat
parseInt - convert string to integer number, if you will float to it then it will give 0,
parseFloat - return number to float,

I was appending the string "Variance: " to the variance variable alongside the actual variance, which when converted to a float still resulted in a NaN. I solved it by swapping this:
variance = parseFloat(variance);
out with this:
variance = parseFloat(+variance.match(/[\d.]+/)[0]);

Related

Not getting the value from document.getElementById method

var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var val = binaryValue.value;
var result = 0;
var i = val.length-1;
var j = 0;
while (i > -1) {
var y = (Number(val[i])) * (2 ** [j]);
result += y;
i--;
j++;
console.log(y);
}
decimalValue.value = result;
console.log(binaryValue.value);
}
Using the code above, I tried to obtain a value from an input field and do a calculation to convert it to a decimal number. But it doesn't obtain the input value. I tried several times and I am unable to figure out it.
This is how you get a value from an input field:
var binaryValue = document.getElementById('binary');
function binaryToDecimal() {
var NumValue = binaryValue.value
console.log("input value: " + NumValue);
//this is how you convert a binary number to decimal
console.log("binary number: " + (NumValue >>> 0).toString(2));
//this is how you convert an decimal number to binary
console.log("decimal number: " + parseInt(NumValue, 2));
}
<input type="text" id="binary" placeholder="insert value"/>
<button type="button" onclick="binaryToDecimal()">Show value</button>
Use this example to fix your code.
I also added ways to convert to and from binary numbers.

Javascript median using for

So I'm trying to learn javascript, and I want to find the median of some numbers that I insert into a prompt when I click on the button "find median".
function Media()
{
var n = prompt("number of elements?");
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
I made a test with two numbers, 1 and 2, and the median was 6, and i cant figure what i've done wrong
You should parse the result of prompt to an integer;
How to convert a string to an integer in JavaScript?
function Media() {
var n = parseInt(prompt("number of elements?"));
var i = 1;
var s = 0;
for (i=1;i<=n;i++)
{
var m = prompt("insert # " +i);
m = parseInt(m);
s = s+m;
}
var media = s/n;
document.getElementById("rezultat").innerHTML = "result: " +media
}
Media();
<div id='rezultat' />
You should also parse the result of prompt using parseInt
var m = parseInt(prompt("insert # " + i));
s/n gives the mean of the input. If you are looking for the median, you should use an array to store the inputs and get the element(s) in the middle.

display in decimal the total of 2 numbers

im trying to display the 2 decimal point of the 2 total number and minus them but it didnt compute the decimal point. anyone would like to figure this out. thanks.
function calculate() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
var basicpay = document.getElementById('basicpay');
var myResult = myBox1 * myBox2;
basicpay.value = myResult.toFixed(2);
document.getElementById('both').value = sum() - diff();
}
this is the diff part
function diff() {
var absent = document.getElementById('absent').value;
var tardiness = document.getElementById('tardiness').value;
var sss = document.getElementById('sss').value;
var pagibig = document.getElementById('pagibig').value;
var philhealth = document.getElementById('philhealth').value;
var cashadvances = document.getElementById('cashadvances').value;
var withholdingtax = document.getElementById('withholdingtax').value;
var others = document.getElementById('others').value;
var result =
parseInt(absent) +
parseInt(tardiness) +
parseInt(sss) +
parseInt(pagibig) +
parseInt(philhealth) +
parseInt(cashadvances) +
parseInt(withholdingtax) +
parseInt(others) || 0;
if (!isNaN(result)) {
document.getElementById('totaldeductions').value = result.toFixed(2);
return result;
}
}
this is the sum part
function sum() {
var basicpay = document.getElementById('basicpay').value;
var overtime = document.getElementById('overtime').value;
var regularholiday = document.getElementById('regularholiday').value;
var specialholiday = document.getElementById('specialholiday').value;
var allowanceday = document.getElementById('allowanceday').value;
var monthpay = document.getElementById('monthpay').value;
var others1 = document.getElementById('others1').value;
var result =
parseInt(basicpay) +
parseInt(overtime) +
parseInt(regularholiday) +
parseInt(specialholiday) +
parseInt(allowanceday) +
parseInt(monthpay) +
parseInt(others1) || 0;
if (!isNaN(result)) {
document.getElementById('totalgrosspay').value = result.toFixed(2);
return result;
}
}
In your Sum() and Diff() function, you are working only with integers. Integers are whole numbers only, so will not retain anything after a decimal point. To deal with decimals, you will need to use JavaScript's parseFloat() function. To give an example, in your Sum() function you would change the result calculation to look like the following:
var result =
parseFloat(basicpay) +
parseFloat(overtime) +
parseFloat(regularholiday) +
parseFloat(specialholiday) +
parseFloat(allowanceday) +
parseFloat(monthpay) +
parseFloat(others1) || 0;
This will retain the decimal points in the numbers rather than truncating to whole numbers as the parseInt()

how to get a float using parseFloat(0.00)

How can I get a float of 0.00. The reason I need 0.00, is because I am going to be accumalating float values by adding. Hence starting with 0.00.
I tried
var tmp ='0.00'
tmp = parseFloat(tmp.toString()).toFixed(2);
totals = parseFloat(tmp)
tmp is 0.00 but totals is 0. How can I make total 0.00? I need it to stay as a float and not a string.
Thanks
You can use the string tmp variable and then when you need to add to it use:
tmp = (+tmp + 8).toFixed(2);
JSFIDDLE DEMO
Or simply write a function to do that seeing that you'll have to do that many times:
function strAdd( tmp, num ) {
return (+tmp + num).toFixed(2);
}
There is no such thing as an integer type in javascript. There is only Number, which is stored as a double precision floating point. So to get a floating point value with 0.00, you need only to do this:
var tmp = 0;
var tmp ='0.00'
tmp = parseFloat(tmp.toString()).toFixed(2);
totals=parseFloat(tmp).toFixed(2);
alert(totals); //0.00
parseFloat() without toFixed() removes zeros after dot. So you need to add toFixed() again.
Here is dynamic floatParser for those who need
function customParseFloat(number){
if(isNaN(parseFloat(number)) === false){
let toFixedLength = 0;
let str = String(number);
// You may add/remove seperator according to your needs
[".", ","].forEach(seperator=>{
let arr = str.split(seperator);
if( arr.length === 2 ){
toFixedLength = arr[1].length;
}
})
return parseFloat(str).toFixed(toFixedLength);
}
return number; // Not a number, so you may throw exception or return number itself
}
You can use parseFloat function in Javascript.
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var a = parseFloat("10") + "<br>";
var b = parseFloat("10.00") + "<br>";
var c = parseFloat("10.33") + "<br>";
var d = parseFloat("34 45 66") + "<br>";
var e = parseFloat(" 60 ") + "<br>";
var f = parseFloat("40 years") + "<br>";
var g = parseFloat("He was 40") + "<br>";
var n = a + b + c + d + e + f + g;
document.getElementById("demo").innerHTML = n;
}
</script>

Find greatest value in array (in set of integers)

My friend asked me to help him with homework, and I'm stuck. Here is assignment:
user must enter in first prompt box number of elements in array. Then, he will get prompt box for each number to enter. Now, output must be greatest number in array. But that simply doesn't work. With my code below, I always get the element who has greatest first digit. (it's doesn't matter if number is negative or positive, code doesn't work as it should)
Here is my code (it even doesn't work in jsfiddle, just in my file)
<button onclick="duzinaNiza()">Do it!</button>
and here is JavaScript
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:");
\\ prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
My friend's proffesor doesn't want to use functions for sorting arrays, this must be done with loops.
P.S. Yeah, I know... But don't ask about document.write thing, it must be printed in that way...
That is because the input is a String, you have to parse it to a Integer. Like:
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
Try this:
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = parseInt(prompt("Enter "+ redniBr +". array number:"));
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
The problem is that you are comparing two strings, when you wanted to compare two numbers.
In other words, the following expression is LEGAL in javascript and evaluates to true:
if('4' > '393939393'){
//true! string '4' is greater than string '3' (first char of '393939393')
}
What you should do is cast the value received from the function prompt, so it is treated as a number. You can do that using the following function:
parseInt(prompt("Enter "+ redniBr +". array number:"), 10);
The first parameter is the value you want to cast to a number, while the second is the radix (or "base") of the number.
So, the main problem here is that you're not threat your numbers as "number", but as string. The method prompt returns a string, so you need to convert them:
function duzinaNiza() {
var brClanova = +prompt("Enter the number of array elements:");
if (!brClanova)
return;
var niz = [];
for (var i=0; i < brClanova; i++) {
var redniBr = i + 1;
niz[i] = +prompt("Enter "+ redniBr + ". array number:");
}
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
}
I used the Unary Plus Operator for that.
Just for to know, in JS you can actually avoid the last loop using Math.max to get the maximum of an array of numbers. So instead of:
var max = niz[0];
for (var a = 1; a < brClanova; a++) {
if (max < niz[a])
max = niz[a];
}
document.write("Greatest value in array is: " + max);
You will have:
var max = Math.max.apply(null, niz);
document.write("Greatest value in array is: " + max);
In that case, you don't even need the unary plus operator because Math.max takes care of that.
try this out, [Tip: i just utilised the '+' operator for casting the value to number (values from prompt.). The '+' operator will return NaN, if the entered value could not get converted into a number. so in that situation, you should use isNan function to get rid of that.]
duzinaNiza = function () {
var brClanova = prompt("Enter the number of array elements:");
if (brClanova > 0) {
var niz = new Array();
var maximum;
for (i=0; i<brClanova; i++) {
var temp = +prompt("Enter "+ i+1 +". number:");
if(i===0) { maximum = temp }
else { maximum = (temp > maximum)?temp:maximum; }
}
alert("Greatest value in array is: " + maximum);
}
}
You don't need parseInt- if you subtract strings that can be converted to numbers, they are converted. So you can subtract the maximum from the next number, and see if it leaves a remainder.
Also, parseInt will destroy decimals, so you won't know that 1.5 is greater than 1.
Your comment used the wrong characters- `('\' should be '//')
function duzinaNiza(){
var brClanova= prompt("Enter the number of array elements:");
if(brClanova>0){
var niz= new Array();
for(var i= 0;i<brClanova;i++){
var redniBr= i+1;
niz[i]= prompt("Enter "+ redniBr +". array number:");
//prompt for geting each array element
}
var maximum= niz[0];
for(var a= 0;a<brClanova;a++){
if(niz[a]-maximum>0){
maximum= niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}
Modified Code JSFIDDLE
function duzinaNiza() {
var brClanova = prompt("Enter the number of array elements:")*1; //convert string to intger
if (brClanova > 0) {
var niz = new Array();
for (i=0; i<brClanova; i++) {
var redniBr = i+1;
niz[i] = prompt("Enter "+ redniBr +". array number:")*1;
// prompt for geting each array element
}
var maximum = niz[0];
for (a=0; a<brClanova; a++) {
if (maximum < niz[a]) {
maximum = niz[a];
}
}
document.write("Greatest value in array is: " + maximum);
}
}

Categories