Javascript Nan Error: parsing strings to ints - javascript

References
How to convert string into float in javascript?
jQuery calculation NaN
Goal
Take two numerical input values from the user.
Divide the second number by the first number.
Multiply the result by 100 so it is represented as a percentage.
Add each number and the result to individual lists.
Call the function getTextInput() via onClick command.
Background
I primarily work with Java; I am currently in a data structures class (second year CS student). My proficiency is intermediate. My familiarity with javascript is basic.
Problem
NaN results. I have tried multiple methods to achieve this task; I parsed both input values and assigned them to new variables, and I parsed both initial string inputs to a float value. However, I am still having a problem parsing the result of these two numbers of type int or string to a float value. Should I be parsing to a float value of parameters of type int? When I convert the string values to int values the program won’t accept the input values and crashes. Why is this happening? I have looked at several related posts, but cannot find anything that provides the information I am looking for. What is the best method to go about this? Any help or direction is greatly appreciated. Thanks.
NOTE Entire code posted at the very bottom.
Method 1 - parsed two strings to float. ‘NaN’ result when I printed percentOfNumbers and percentageList to the console.
var num1 = document.getElementById("numString1");
var num2 = document.getElementById("numString2");
percentOfNumbers = parseFloat(num2/num1 * 100); percentageList.push(percentOfNumbers);
percentOfNumbers.value = "";
// add num1 to List1
List1.push(num1.value);
num1.value = "";
// add num2 to List2
List2.push(num2.value);
num2.value= "";
Method 2 - parsed each text input to an int value, parsed the result to a float value. ‘NaN’ result when I printed percentOfNumbers and percentageList to the console.
var num1 = document.getElementById("numString1");
var num2 = document.getElementById("numString2");
var num1Parsed = parseInt(num1);
var num2Parsed = parseInt(num2);
percentOfNumbers = parseFloat(num2Parsed/num1Parsed * 100); percentageList.push(percentOfNumbers);
percentOfNumbers.value = "";
// add num1 to List1
List1.push(num1Parsed.value);
num1Parsed.value = "";
// add num2 to List2
List2.push(num2Parsed.value);
num2Parsed.value= "";
// EXAMPLE INPUT VALUES, 2000 for num1, 2233 for num2
// Entire Code
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
--><!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script>
// separate lists for repeat user input values for num1, num2, and percentageOfNumbers
var List1 = [];
var List2 = [];
var percentageList = [];
var percentOfNumbers = 0;
var num1Parsed = 0;
var num2Parsed = 0;
function getTextInput() {
// retrieve two numbers of type 'String' from user and assign to appropriate var
var num1 = document.getElementById("numString1");
var num2 = document.getElementById("numString2");
// parse each string input number into an int
num1Parsed = parseInt(num1);
num2Parsed = parseInt(num2);
// divide second number by first number
// parse result and assign to percentOfNumbers var
// add percentOfNumbers value to percentageList
// reassign percentOfNumbers to ""
percentOfNumbers = (num2Parsed/num1Parsed * 100);
percentageList.push(percentOfNumbers);
percentOfNumbers.value = "";
// add num1 to List1
List1.push(num1Parsed.value);
num1Parsed.value = "";
// add num2 to List2
List2.push(num2Parsed.value);
num2Parsed.value= "";
}
</script>
</head>
<body>
<input id="numString1" type="text" name="input1" value="" />
<input id="numString2" type="text" name="input2" value="" />
<input id="inputField" type="button" name="search" value="compute" onClick="getTextInput();" />
</body>
</html>

The num1 and num2 variables doesn't contain strings, they contain the DOM elements.
Use the value property to get the value from the input fields:
var num1 = document.getElementById("numString1").value;
var num2 = document.getElementById("numString2").value;
Numbers however doesn't have a value property. You want to push the number itself:
List1.push(num1Parsed);
List2.push(num2Parsed);
Side note: Specify the base when you use parseInt, as numbers with leading zeroes are parsed using base 8 instead of 10:
num1Parsed = parseInt(num1, 10);
num2Parsed = parseInt(num2, 10);

Related

I Want get a value by javascript sum value onclick function result is good but i want to fix value 2 dicimal?

I have need no large dicimal value only 2 need dicimal value so please help...
<script>
$(function() {
$("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown keyup", sum);
function sum() {
$("#trec").val(Number($("#isum").val()) / Number($("#num2").val()));
$("#trec").val(Number($("#trec").val()) * Number($("#rec2").val()));
//-----------------------------
$("#rec1").val(Number($("#num1").val()));
$("#difnum1").val(Number($("#rec1").val()));
//-----------------------------
$("#rec3").val(Number($("#num3").val()));
$("#difnum3").val(Number($("#rec3").val()));
//-----------------------------
$("#difnum2").val(Number($("#num2").val()) - Number($("#rec2").val()));
$("#tdifnum").val(Number($("#isum").val()) - Number($("#trec").val()));
}
});
</script>
If you already have an existing numeric value, you can use the Number.toFixed() function to specify the number of significant digits that you want to include after the decimal point.
So in your case, you would just want to perform your calculations and add the .toFixed(2) following them:
// Example
$("#difnum2").val((Number($("#num2").val()) - Number($("#rec2").val())).toFixed(2));
For the sake of readability, you may want to consider parsing all of your values separately and performing your calculations using those:
$(function() {
$("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown keyup", sum);
function sum() {
// Get your values
var isum = Number($($"#issum").val()),
num2 = Number($("#num2").val()),
rec2 = Number($("#rec2").val()),
num1 = Number($("#num1").val()),
rec1 = Number($("#rec1").val()),
num3 = Number($("#num3").val()),
rec3 = Number($("#rec3").val());
// Perform your calculations
var trec = (isum / num2) * rec2,
difnum2 = num2 - rec2,
tdifnum = isum - trec;
// Set your values
$("#trec").val(trec);
$("#rec1").val(num1);
$("#difnum1").val(rec1);
$("#rec3").val(num3);
$("#difnum3").val(rec3);
$("#difnum2").val(difnum2);
$("#tdifnum").val(tdifnum);
}
});
I'd also recommend considering some more meaningful names as to what each of these values are (and what is being calculated) as opposed to arbitrary names (e.g. num1, num2, rec1, rec2, etc.)
You just add toFixed in the last of your decimal value.
function myFunction() {
var num = 1.122341345;
var n = num.toFixed(2);
document.getElementById("demo").innerHTML = n;
}
<p>Click the button to display the fixed number.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
For your reference check this link : https://www.w3schools.com/jsref/jsref_tofixed.asp
As your code shows jquery, try this : jQuery limit to 2 decimal places
this way you can acheive:
When you define a var, in JavaScript it is a string, so you need to parse.
According to #Rion Williams stated , with number you can directly use toFixed() as it is just number which is going to convert in float value
(function() {
$("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown keyup", sum);
function sum() {
$("#trec").val((Number($("#isum").val()) / Number($("#num2").val())).toFixed(2));
$("#trec").val((Number($("#trec").val()) * Number($("#rec2").val())).toFixed(2));
//-----------------------------
$("#rec1").val((Number($("#num1").val())).toFixed(2));
$("#difnum1").val((Number($("#rec1").val())).toFixed(2));
//-----------------------------
$("#rec3").val((Number($("#num3").val())).toFixed(2)); $("#difnum3").val((Number($("#rec3").val())).toFixed(2));
//-----------------------------
$("#difnum2").val((Number($("#num2").val()) - Number($("#rec2").val())).toFixed(2)); $("#tdifnum").val((Number($("#isum").val()) - Number($("#trec").val())).toFixed(2));
}
});

Is there an alternative to toFixed() in Google Apps Script?

I'm looking for a way to force a var to 2 decimal places, unfortunatly formatting the cell in sheets only works when the number is not part of a larger string so I need the value to be exact. Example below:
function onOpen() {
var submenu = [{name:"ERROR TEST", functionName:"errorTest"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('RUN', submenu);
}
function errorTest(){
var ss = SpreadsheetApp.getActive();
var num = ss.getRange("A1").getValues(); //gets number 22.34567 out of A1
var n = num.toFixed(2);
var text = "Price of your item: £" + n;
ss.getRange("B1").setValue(text);
}
The problem is this results in the error "TypeError: Cannot find function toFixed in object 22.34567."
Is there an alternative to this that will remove/ pad a number to 2
decimal places?
If not does anyone know how to make a version of toFixed() so I can
create it in scripts myself?
Thank you very much.
You are calling the getValues() function which returns a two-dimensional array of objects/values.
JavaScript / Google Apps Script is good at changing between types but it won't recognise your variable num as a number, it sees it as a two-dimensional array of numbers.
If you call getValue() then you get a single object and Google Apps Script can treat it as a number allowing you to call the toFixed() function:
function errorTest(){
var ss = SpreadsheetApp.getActive();
var num = ss.getRange("A1").getValue(); //gets number 22.34567 out of A1
var n = num.toFixed(2);
var text = "Price of your item: £" + n;
ss.getRange("B1").setValue(text);
}

Input field values not arithmetically summing up

Goodday, please i have a code to calculate the efficiency of a generator. The problem is the input fields all add up until the last variable. If all values were 2+2+3+4 which normally sums up into 11 normally, this program doesn't do that instead it just adds the 4 as in 2+2+3+4 equals 74.
That's the formula for calculating the efficiency of a generator.
$('.efmit').on('click', function efficiency() {
var vI = $('.I').val();
var vV = $('.V').val();
var ia = $('.ia').val();
var If = $('.If').val();
var Ra = $('.Ra').val();
var closs = $('.closs').val();
var vi_combo = vI*vV;
var ias = (ia*ia)*Ra;
var iv = If*vV;
var cent = 100;
var result = vi_combo+ias + iv;
var finalR = result + closs;
window.alert(finalR);
})
jQuery val method like $('.closs').val() returns String type variable not Number type.
You can cast type of variable to solve the problem.
var closs = Number($('.closs').val());
The reason is your program treated your variable as a string
try converting them to integer by parsing them like this parseInt(yourVariable).

Math Input, Calculate, and Output Javascript with Fractions/Decimals

I was wondering if it was possible for a program in Javascript to receive fractions as input and use these fractions to calculate certain values. I have attempted to make a calculator of percentage difference (physics) which uses the formula ((|max-min|)/((max+min)/2))*100. I already understand how to manipulate the input and split it in an array. As such, I stored the max and min values in val1 and val2. However, the issue comes with the computation. Originally I clumped the whole formula in a single statement, but it didn't work. Thus, I separated the calculations into steps and stored the value in variables after each step to make sure it did the computations properly. This is what I have:
var step1=Math.abs(val1-val2);
var step2=val1+val2;
var step3=step2/2;
var step4=step1/step3;
var final=Math.round(step4*100*100)/100;
However, there are still a lot of glitches going on with the computations, especially with fractions and decimals. For example, the percentage value when 90/100 and 89/100 are inputted would be FAR different from if 9/10 and 89/100 are placed. Occassionally, inputting decimals return NaN. I really don't understand what's going on. Anyone who can highlight what's wrong with the above code in computing percentage difference or teach me how Javascript computes and show how the computations are in line with the outputs I receive would definitely help.
Thank You. :)
If it's any help, this is the full code of the program. You can ignore this if it isn't necessary in solving the problem. I've deleted all completely unnecessary parts of the code to the problem.
<html>
<head>
<title></title>
</head>
<style type="text/css">
</style>
<script>
var def;
function submit() {
var e = document.getElementById("topic");
var ter = document.getElementById("term").value;
var strUser = e.options[e.selectedIndex].value;
if (!strUser) {
document.getElementById("textcom").value = "Please specify what needs to be solved.";
}
else if (!term) {
document.getElementById("textcom").value = "Please specify the values used to calculate.";
}
else {
if (strUser == "a") {
var arr = ter.split(",");
var val1 = parseInt(arr[0]);
var val2 = parseInt(arr[1]);
if (arr.length > 2 || arr.length < 2) {
def = "Error. Incorrect number of values written.";
}
else if (isNaN(val1) || isNaN(val2)) {
def = "Error. One or more values input is/are not a number.";
}
else {
var step1 = Math.abs(val1 - val2);
var step2 = val1 + val2;
var step3 = step2 / 2;
var step4 = step1 / step3;
var final = Math.round(step4 * 100 * 100) / 100;
def = final + "%";
}
}
document.getElementById("textcom").value = def;
}
}
</script>
<body>
<h1>Physics Calculator</h1>
<span>Please choose desired solution:</span>
<select id="topic">
<option disabled selected value>------ Option ------</option>
<option value="a">Percent Difference</option>
</select>
<br>
<span>Values:</span>
<input type="text" id="term"></input>
<br>
<br>
<textarea rows="20" cols="40" id="textcom">Uneditable. For output purposes only.</textarea>
<br>
<button onclick="submit()">Submit</button>
<script>
document.getElementById("textcom").readOnly = "true";
</script>
</body>
</html>
It seems like you expect JavaScript to recognise fractions like 12/100 as numerical values when applying parseInt to them.
This is not the case because:
A division (/) is an operator in JavaScript (and most other languages), not a numerical notation (like the decimal .). Characters like / are not allowed in numerical literals.
Even if you enter numbers as decimals (like 15.89), the function parseInt will ignore the decimal parts -- the name of parseInt already reveals this behaviour. You should use parseFloat, or shorter, apply the unitary + to the string, which implicitly converts it to a number.
To solve this, you could write a function that turns fractional notations into the numbers they represent. I have called that function evaluate in the snippet below:
// To interpret fractions (with '/') as numbers:
function evaluate(term) {
// remove spaces and get numerator and denominator
var arr = term.replace(/ /g, '').split('/');
// get part before '/' and turn into number
var val = +arr.shift();
// read denominator(s) and perform division(s)
while (arr.length) {
val = val / +arr.shift();
}
return val;
}
function submit() {
var e = document.getElementById("topic");
var ter = document.getElementById("term").value;
var strUser = e.options[e.selectedIndex].value;
var def;
if (!strUser) {
def = "Please specify what needs to be solved.";
}
else if (!term) {
def = "Please specify the values used to calculate.";
}
else if (strUser == "a") {
var arr = ter.split(",");
var val1 = evaluate(arr[0]);
var val2 = evaluate(arr[1]);
if (arr.length !== 2) {
def = "Error. Incorrect number of comma-separated values written; two expected.";
}
else if (isNaN(val1) || isNaN(val2)) {
def = "Error. One or more values input is/are not a number.";
}
else {
var step1 = Math.abs(val1 - val2);
var step2 = val1 + val2;
var step3 = step2 / 2;
var step4 = step1 / step3;
var final = Math.round(step4 * 100 * 100) / 100;
def = final + "%";
}
}
document.getElementById("textcom").value = def;
}
<span>Please choose desired solution:</span>
<select id="topic">
<option disabled selected value>------ Option ------</option>
<option value="a" selected>Percent Difference</option>
</select>
<br>
<span>Values:</span>
<input type="text" id="term"></input>
<br>
<br>
<textarea readonly rows="3" cols="40" id="textcom">Uneditable. For output purposes only.</textarea>
<br>
<button onclick="submit()">Submit</button>
NB: note that you can use the readonly attribute in HTML -- no need to set this via JavaScript.

Javascript Count numbers

This probably is a very easy solution, but browsing other questions and the internet did not help me any further.
I made a javascript function which will give me a random value from the array with its according points:
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
document.getElementById("Points").innerHTML += punten;
}
I've added a += punten so i can see that it works correctly. It shows me all the point in the div with the id Points.
But what i wanted to do is count it all together so if i were to draw a 4, King and a 10 it should show 24 instead of 41010.
Thanks in advance! And if you're missing any information please let me know
Currently you are just adding strings together, which concatenate (join together) hence why you end up with 41010. You need to grab the current innerHTML (total) and use parseInt() to convert from a string to a number, then add your new cards that have been chosen, then assign this new value to the innerHTML of your element.
Try the following
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
var total = curPoints + parseInt(punten, 10);
document.getElementById("Points").innerHTML = total;
}
More info on parseInt() here
EDIT
I've added this line -
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
Which will try and convert the innerHTML of the "Points" div, but if it is empty (an empty string converts to false) then curPoints will be equal to 0. This should fix the issue of the div being blank at the start.
innerHTML is a string and JavaScript uses + for both string concatenation as numeric addition.
var pointsInHtml = parseInt(document.getElementById("Points").innerHTML, 10);
pointsInHtml += punten;
document.getElementById("Points").innerHTML = punten;
The second parameter 10 of the parseInt method is usually a good idea to keep there to avoid the function to parse it as an octal.
It might be easier to keep a points variable and only at the end put it in the #Points container, that would make the parseInt no longer necessary
innerHTML will be a string, so you need to convert it into an integer prior to adding the card value :)
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1],
curPunten = parseInt(document.getElementById('Points').innerHTML);
document.getElementById("Points").innerHTML = curPunten + punten;
}

Categories