JS GPA calculator change to 3 decimals - javascript

My calculator is rounding to 2 decimal places. How do I change it to 3 decimal places?
function formatDecimal(aFloat) {
var digits = "" + Math.round(100 * aFloat);
var length = digits.length;
if (length < 3) {
return "0." + digits;
}
else {
var dp = length - 2;
return digits.substring(0, dp) + "." + digits.substring(dp, length);
}
}
//Return the char of aString at index.
//If index is invalid, the results are undefined.
function charAt(aString, index) {
var length = aString.length;
return aString.substring(index, index + 1);
}

Related

Only accept whole numbers, no decimals

I need my code to only accept whole numbers, no decimals and should prompt an error when a decimal gets entered. I don't want a new function , I'm hoping I can just add lines to my function but I don't know what I need to add.
function number_function() {
number = parseInt(prompt('Enter a positive integer:'));
if (number < 0) {
alert('Error! Factorial for negative number does not exist. But I will show you the positive number');
number = number * -1;
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
} else if (number === 0) {
alert("Please enter a number greater than 0");
} else {
let n = 1;
for (i = 1; i <= number; i++) {
n *= i;
}
alert("The factorial of " + number + " is " + n + ".");
}
}
number_function();
You can do this to check if the number has decimals
const val = 10.7 % 1;
if (val !== 0) {
console.log('has decimals');
} else {
console.log('has no decimal');
}
JavaScript provides the built-in function Number.isInteger(n)

How to find the average in javascript?

So I'm fairly new to JavaScript but I cannot seem to find the average in my code. I want to understand why my average is not working. Any help you guys?
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
} else {
oddSum += num;
}
evenAvg = evenSum / num;
oddAvg = oddSum / num;
}
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
On your code, to calculate the oddAvg and evenAvg, you have divided evenSum and oddSum by num variable (which is input from prompt).
And as you know, average = total sum / total count, so it's not right to divide the sum by the input number variable.
Instead of that, you need to calculate the count of odd and even numbers and divide the even and odd sum by the even and odd number counts as follows.
function getEvenOdd() {
var oddSum = 0;
var evenSum = 0;
var num = 0;
var evenAvg = 0;
var oddAvg = 0;
var evenCount = 0;
var oddCount = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenSum += num;
evenCount ++;
} else {
oddSum += num;
oddCount ++;
}
}
evenAvg = evenSum / evenCount;
oddAvg = oddSum / oddCount;
alert("Sum of all even numbers is: " + evenSum);
alert("Sum of all odd numbers is: " + oddSum);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();
These operations are dividing the evenSum or oddSum by the last input num.
evenAvg = evenSum / num;
oddAvg = oddSum / num;
You should divide the sum by the number of even or odd inputs.
Instead of evenSum / num use evenSum/Count of Numbers entered.
How about this solution? It is aiming to store odd and even numbers into oddList and evenList.
function getEvenOdd() {
var evenAvg = 0;
var oddAvg = 0;
var oddList = [];
var evenList = [];
var num = 0;
while (true) {
num = parseInt(prompt("Enter a number(-1 to exit)"));
if (num == -1) {
break;
}
if (num % 2 == 0) {
evenList.push(parseInt(num));
} else {
oddList.push(parseInt(num));
}
evenAvg = evenList.reduce((p, c) => p + c, 0) / evenList.length;
oddAvg = oddList.reduce((p, c) => p + c, 0) / oddList.length;
}
alert("Sum of all even numbers is: " + evenList.length);
alert("Sum of all odd numbers is: " + oddList.length);
alert("Average of all even numbers is : " + evenAvg);
alert("Average of all odd numbers is: " + oddAvg);
}
getEvenOdd();

application spits the numbers back at me even though it should return another value

I'm trying to make this front end web application where you provide acres and karats in a prompt in this form e.g. 3.22 and calculates them and give the total back in the chrome JS console
For example, you have 3.22 acres of land and another land that is 2.2 acres. If you get the sum of these numbers it should give you 5.42, no I want them to return 6, because acres have 24 karats and if you calculate 3 acres and 22 karats + 2 acres and 2 karats it should give you 6 acres, that's what I'm trying make here. I've been trying all night and every time the numbers I put in the prompt gets spit back at me in the console, so here's my code:
window.setTimeout(function() {
var acres = [];
var floats = [];
var wholes = [];
var input = prompt("What would you like to do?");
while (input !== "quit") {
if (input === "total") {
console.log("***********");
acres.forEach(function(total, i) {
console.log(i + ": " + total);
})
console.log("***********");
} else if (input === "calc") {
var num = prompt("Please enter a number");
while (num !== "back") {
if (num === "back") {
break;
}
acres.push(num);
var ftotal = 0
var wtotal = 0;
floats = [];
wholes = [];
for(var i = 0; i < acres.length; i++) {
alert("entered the for loop");
var acresNum = acres.pop();
var str = acresNum.toString();
var number = Math.floor((str).split(".")[1]);
floats.push(number);
ftotal += floats[i];
//-------------------------
var num2 = Math.floor(acresNum);
wholes.push(num2);
wtotal += wholes[i];
}
alert("exited the for loop");
console.log(ftotal);
console.log(wtotal);
if (ftotal > 23) {
wtotal++;
}
acres.push(wtotal + "." + ftotal);
var num = prompt("Please enter a number");
}
}
var input = prompt("What would you like to do?");
}
console.log("OK, YOU QUIT THE APP");}, 500)
The whole logic in this application is in that for loop in the else if(input === "calc") area.
You could take a numerical approach, but you went into the trap of floating point arithmetic (Is floating point math broken?) and get a number which does not match the given value of 42.
function sum(a, b) {
var s = a + b,
i = Math.floor(s),
p = (s - i) * 100;
console.log(p);
if (p >= 42) { // never reached
p -= 42;
++i;
}
return i + p / 100;
}
console.log(sum(3.22, 2.2));
As solution, you could separate the places as a string and add integer values and check if the value is greater than one acre, then return an adjusted value.
function sumD(a, b, threshold) {
return [a, b]
.map(v => v.toString().split('.'))
.reduce((r, a) => {
a.forEach((v, i) => r[i] += +v);
r[0] += Math.floor(r[1] / threshold);
r[1] %= threshold;
return r;
}, [0, 0])
.join('.');
}
console.log(sumD(3.22, 2.2, 24));
Separate the decimal values from your numbers.(Already done)
Ex: 3.22 -> 0.22 and 2.2 -> 0.2
Add them -> 0.22 + 0.2
Divide them by 0.24 -> (0.22+0.2)/.24 = 1
Add that to the wtotal -> 3.00 + 2.00 = 5 -> 5 + 1
I think this should be the logic mathematically.

Converting integer to decimal using JavaScript

I have a program that needs to convert integers to binary and decimal. I have the binary portion working but am stuck on the decimal part. I'm trying to use intToFloat but not sure if that's right. Here is the code for the conversion functions.
if (cT[0].checked) {
// to binary
var dval = parseInt(val);
if (isNaN(dval)) {
alert("input value is not a number");
}
else if ((val % 1) !== 0 ) {
alert("number is not a integer");
}
else if (dval < 0) {
alert("Input value must be a positive integer");
}
else {
convertByArray(dval);
}
}
else if (cT[1].checked) {
//to decimal
var dval = parseFloat(val);
if (isNaN(dval)) {
alert("input value is not a number");
}
else if ((val % 1) !== 0 ) {
alert("number is not a integer");
}
else if (dval < 0) {
alert("Input value must be a positive integer");
}
else {
intToFloat(dval);
}
}
else {
alert("Please select a conversion type.");
}
}
function convertByArray(dval) {
var rA = new Array();
var r,i,j;
i=0;
while (dval > 0) {
r = dval % 2;
rA[i] = r;
var nV = (dval - r) / 2;
$("txtCalc").value = $("txtCalc").value + " Decimal " + dval + " divided by 2 = "
+ nV + " w/Remainder of: " + r + "\n";
i += 1;
dval = nV;
}
for(j=rA.length-1; j>= 0; j--) {
$("txtOut").value = $("txtOut").value + rA[j];
}
}
function intToFloat(num, decPlaces) {
return num + '.' + Array(decPlaces + 1).join('0');
}
I need it to show the output of an integer being converted to a decimal and show the value as well, like it already does when it converts to binary.
parseInt(value, fromBase).toString(toBase)
To convert it to binary
parseInt(25,10).toString(2) //<== '25' is the value, 10 is the current base. 2 is the base you want to converted.
To convert it to decimal
parseInt(100011,2).toString(10)
To convert it to float
var num = 203
num.toFixed(6) // asnwer will be 203.000000

How do I get this script to run return the needed values of min max and sum

Here is the link to the JSFiddle
var num = prompt("Enter numbers seperated by spaces");
num = [];
var max = function (num) {
var largest = num[0];
for (var i = 1; i < num.length; i += 1) {
if (num[i] > largest) {
largest = num[i];
}
}
return largest;
};
var min = function (num) {
var smallest = num[0];
for (var i = 1; i > num.length; i -= 1) {
if (num[i] > smallest) {
smallest = num[i];
}
}
return smallest;
};
var sum = function (num) {
};
return("Minimum is " + min + ", Maximum is " + max + ", Sum is " + sum + ".");
alert(return);
I need the script to return the numerical values in the sentence that is in in return()
As was already mentioned by #JJPA you have multiple problems with your code. And you have to fix them if you want to make it working.
However if you want to learn new approaches, which could make your task easier and shorter, you may have a look at this alternative solution:
function worker(str) {
var numbers = str.split(/\s+/).map(Number),
max = Math.max.apply(this, numbers),
min = Math.min.apply(this, numbers),
sum = numbers.reduce(function(a, b) { return a + b });
return 'Minimum is ' + min + ', Maximum is ' + max + ', Sum is ' + sum + '.';
}
alert( worker(prompt()) );
It does exactly what you want but here you use all power of JavaScript array and math methods.
First, you are reading from prompt and you initialized that variable to new array. Below lines. So you don't have any values left in num.
var num = prompt("Enter numbers seperated by spaces");
num = [];
Second, you get SyntaxError: Unexpected token return because you have used return in a wrong way. Read about return by searching.
Third, you are not calling the methods min, max and sum properly.
An example code would be like below,
var num1 = prompt("Enter numbers seperated by spaces");
var num = num1.split(' ');
console.log(typeof (num));
var max = function (num) {
var largest = num[0];
for (var i = 1; i < num.length; i += 1) {
if (num[i] > largest) {
largest = num[i];
}
}
return largest;
};
var min = function (num) {
var smallest = num[0];
for (var i = 1; i > num.length; i -= 1) {
if (num[i] > smallest) {
smallest = num[i];
}
}
return smallest;
};
var sum = function (num) {
};
alert("Minimum is " + min(num) + ", Maximum is " + max(num) + ", Sum is " + sum(num) + ".");
EDIT :
replace the sum with below. Adding a return statement would solve undefined problem.
var sum = function (num) {
var s = 0;
for (var i = 0; i < num.length; i++) {
s = s + parseInt(num[i], 10);
}
return s;
};
return returns values from a function. One solution here is to take the user-input, add it as parameter when you call a function and have the result of that function return you the information you need. Here's your code rewritten to use the short-hand versions that JS allows:
var num = prompt("Enter numbers separated by spaces");
function getValues(num) {
// split the user input into an array
// and convert the string values to integers
var arr = num.split(' ').map(Number);
// Use the Math functions to get the max and min values from the array
var max = Math.max.apply(null, arr);
var min = Math.min.apply(null, arr);
// Reduce allows you to grab the sum of the values
var sum = arr.reduce(function (p, c) { return p + c; });
// return an object with all the values attached
return { max: max, min: min, sum: sum };
}
// get the result by passing in num
var result = getValues(num);
console.log(result); // { max=66, min=1, sum=79 }
console.log(result.max) // 66
console.log(result.min) // 1
console.log(result.sum) // 79
Hope it's of some use.
Demo

Categories

Resources