Javascript handling fractions in variables - javascript

I'm new to programming and was trying to write a simple program to find the slope of a line, and I was wondering how I could handle variables with fractions in them. Currently, if I assign any of the variables as a fraction I will get an error.
var oneX = prompt ("what is the X of the first coordinate?");
var oneY = prompt ("what is the Y of the first coordinate?");
var twoX = prompt ("what is the X of the second coordinate?");
var twoY = prompt ("what is the Y of the second coordinate?");
console.log(oneX);
console.log(oneY);
console.log(twoX);
console.log(twoY);
var yRes = twoY-oneY;
var xRes = twoX-oneX;
console.log(yRes);
console.log(xRes);
var slope = yRes/xRes
console.log(slope);
If you have any advice for making this program neater too, I'd be happy for it. Thanks!

Dont use eval! Unless you know what eval is, why you should and shouldnt use it.
If you simply want to allow fractions then you should allow for parsing it. For instance you could simple write your code as such:
/*
* Tries to parse a users input, returns {#param input} as a number or
* attempts to parse the input as a fraction.
* #return Number or NaN if an invalid number or unparseable
*/
function parseUserInput(input) {
var res = +input;
if(isNaN(res)) {
// try parsing as fraction
var strval = String(input);
var ix = strval.indexOf('/');
if(ix !== -1) {
try {
res = strval.substring(0, ix) / strval.substring(ix+1);
} catch(e) {
}
}
}
return isFinite(res) ? res : NaN;
}
var oneX = parseUserInput(prompt ("what is the X of the first coordinate?"));
var oneY = parseUserInput(prompt ("what is the Y of the first coordinate?"));
var twoX = parseUserInput(prompt ("what is the X of the second coordinate?"));
var twoY = parseUserInput(prompt ("what is the Y of the second coordinate?"));
Or a very pretty way of writing it using #Jonasw's suggestion.
/*
* Tries to parse a users input, returns {#param input} as a number or
* attempts to parse the input as a fraction.
* #return Number or NaN if an invalid number or unparseable
*/
function parseUserInput(input) {
return +input.split("/").reduce((a,b)=> a/(+b||1));
}

Related

can't get the output from javascript

var weightkg=document.getElementById('weight').value;
var heightinm=document.getElementById('height').value;
function bmival (weightkg,heightinm){
var hout=heightinm*2
var output=weightkg/hout
//make a full number
// var r= Math.trunc(o)
if (output<=18.5){
return document.getElementById('print').innerHTML=`Your BMI is ${output} you are underweight` ;
}
else if(output>18.5 && o<25.5){
return document.getElementById('print').innerHTML=`Your BMI is ${output} You come under fit catogery`;
}
else{
return document.getElementById('print').innerHTML=`Your BMI is ${output} you are overweight and obese`;
}
}
[i am making a bmi cal that take input from user but i am getting a error and don't know what i am doing wrong]
**
this is js code and when i run i get a NaN instead of Number **
The values from an input field are strings so you must convert them into numbers
var heightinm = +document.getElementById('height').value; // one way to do it.
The value you get from
var weightkg=document.getElementById('weight').value;
seems to be a string instead of number. You need to convert values to do Math operations on them. NaN tells you output is not a number. Turn your values to number with parseInt method.
var weightkg = parseInt(document.getElementById('weight').value);
or you can just put a "+" to convert a string into number
var weightkg = +document.getElementById('weight').value;
For Example.
const input = document.getElementById('input');
const defaultStringInput = document.getElementById('input').value;
const inputConverted = parseInt(document.getElementById('input').value);
const inputConverted2 = +document.getElementById('input').value;
input.addEventListener('change', () => {
console.log(typeof defaultStringInput); // string
console.log(typeof inputConverted); // number
console.log(typeof inputConverted2); // number
});

Rounding output to 2 decimals

I've coded a small compound interest calculator. The last output-field has to show the amount calculated with the inputs above. But it should be rounded to two decimals and I didn't get it to work with various code-snippets I found on the web and even stackoverflow.
var $button9 = $('.increment-btn5'); // button to call the function below
var $counter1 = $('.counter1'); // First input
var $counter2 = $('.counter2'); // obsolete var at the moment
var $counter3 = $('.counter3'); // Second input
var $counter4 = $('.counter4'); // Third input
var $counter5 = $('.counter5'); // Ouput
$button9.click(function(){
$counter5.val( parseInt($counter1.val()) * ((parseInt($counter4.val()) / 100) + 1) ** parseInt($counter3.val() ) ); // Calculates amount and loads it into .counter5
Useful ideas would be highly appreciated, thanks.
Have you tried using Number.toFixed yet?
var $button9 = $('.increment-btn5'); // button to call the function below
var $counter1 = $('.counter1'); // First input
var $counter2 = $('.counter2'); // obsolete var at the moment
var $counter3 = $('.counter3'); // Second input
var $counter4 = $('.counter4'); // Third input
var $counter5 = $('.counter5'); // Ouput
$button9.click(function(){
$counter5.val(
( // begin calculation
parseInt($counter1.val()) *
((parseInt($counter4.val()) / 100) + 1) **
parseInt($counter3.val() )
) // end calculation
.toFixed(2) // round it to two decimals
); // pass it to counter5
});

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).

getting NaN message in javascript while adding up multiple text fields

I am developing a simple application form where I am calculating experiences from maximum three employers. Now I want to add them up . The experiences are in the form of X years Y months and Z days. I have written following javascript function --
function total(){
var td;
var fd=parseInt(document.getElementById("LoS_days1").value);
var sd=parseInt(document.getElementById("LoS_days2").value);
var ld=parseInt(document.getElementById("LoS_days3").value);
var tm;
var fm=parseInt(document.getElementById("LoS_months1").value);
var sm=parseInt(document.getElementById("LoS_months2").value);
var lm=parseInt(document.getElementById("LoS_months3").value);
var ty;
var fy=parseInt(document.getElementById("LoS_year1").value);
var sy=parseInt(document.getElementById("LoS_year2").value);
var ly=parseInt(document.getElementById("LoS_year3").value);
td = (fd +sd +ld);
var rd = td%30;
var cm = Math.floor(td/30);
document.getElementById("Totalexp_day").value=rd;
tm = (cm + fm +sm +lm);
var rm = tm%12;
var cy = Math.floor(ty/12);
document.getElementById("Totalexp_month").value=rm;
ty = (cy + fy +sy +ly);
document.getElementById("Totalexp_year").value=ty;
}
I am getting a NaN message in each of the Totalexp_day, Totalexp_month and Totalexp_day field. Earlier I had some modified code that was not showing NaN message but it was not showing the desired results. Kindly suggest what to do to eliminate these two errors.
parseInt(document.getElementById("LoS_days1").value)
if the first character of the string cannot be converted to a number, parseInt will return NaN.
To avoid this, you can so something like is suggested here:
parseInt(document.getElementById("LoS_days1").value) || 0
If document.getElementById("Totalexp_day").value is empty then also it will return NaN. Make sure you have some number there.
Second alternative is reading document.getElementById("Totalexp_day").innerHTML and then applying parseInt
Probably you alert or console log the document.getElementById("Totalexp_day").value you would be more clearer why this problem is comming

matching two fields in a form from two functions in javascript

I have two fields that I'd like to match. (already done the validation functions for field 1 and 2)
field01 has a client number Txxxxx xxxxx (can be T G or M)
field02 has the area code 416 / 905 / 647
I'd like to match T with 416, G with 905, and M with 647.
and show a relationship error if the rules were broken.
I made a separate function trying to compare the two.
function validatecompare(errMessages)
{
var clientID = document.pizza.field02;
var telenum = document.pizza.field03;
var client = clientID.value;
var phone = telenum.value;
var firstL = "";
var areaC = "";
firstL=client.substr(0,1);
areaC =phone.substr(0,3);
if ((firstL) !=areaC)
{
errMessages += "<li>Client Number and Telephone No. are not consistent with our set up rules.</li>\n";
}
return errMessages;
}
I know that's wrong, I just have no idea how to compare two fields from two separate functions. The error message will pop up regardless of what I do. Even if I violate the rules for field 1 and 2 the error message will pop up with those when it shouldn't.
If there is somewhere I can read up on how to do this would be excellent for future reference.
any help would be greatly appreciated, thanks.
You're literally comparing 416 and T. You need some kind of lookup table:
function validatecompare(errMessages) {
var clientID = document.pizza.field02;
var telenum = document.pizza.field03;
var client = clientID.value;
var phone = telenum.value;
var firstL = client.charAt(0);
var areaC = phone.substr(0, 3);
var areaCodes = {
'416': 'T',
'905': 'G',
'647': 'M'
};
if(firstL !== areaCodes[areaC]) {
errMessages += "<li>Client Number and Telephone No. are not consistent with our set up rules.</li>\n";
}
return errMessages;
}

Categories