Rounding output to 2 decimals - javascript

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
});

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
});

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

Javascript handling fractions in variables

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));
}

Jquery calculating problems

I'm trying to create a script that get some values from several selectboxes and then do some math with them.
The problem is that the script need to be placed in a SaaS enviroment so my options of doing stuff are every limited. The way described below is the only way to do this.
The problem I'm facing is that I can receive the correct values from the selectboxes but I can't convert them to 2 decimals. Further I can't get the initial value adviesprijs converted to just eg. 1500 instead of 1.5 or 1.500.00. I really can't see what I'm doing wrong.
I've created a fiddle here I think that describes my problem best!
My script
function update_amounts() {
var perc = '10' || 0; //this is a value from a Twig tag. Not relevant for question!
var korting = ((100-perc)/100);
var adviesprijs = '€1.500,00'.replace(/[^\d.]/g, ''); //gives 1.5 or 1.500.00 etc..
var adviesprijsValue = parseFloat(adviesprijs) || 0;
var sum = 0.0;
$('#product_configure_form .product-configure-custom-option select').each(function () {
var optionText = $(this).find('option:selected').text();
var matches = optionText.match(/\(([^)]+)\)/g) || [];
if (matches.length > 0) {
var priceText = matches[matches.length - 1];
if (priceText.indexOf("€") > -1) {
var priceClean = priceText.replace(/[^0-9\+\-\.\,]/g, '');
var priceValue = parseFloat(priceClean) || 0;
sum += priceValue;
}
}
});
var sum2 = sum+adviesprijsValue;
var sumBtw = (sum2*1.21).toFixed(2);
$('#amount').text('€' +sum2);//
$('#amountBtw').html('(€'+sumBtw+' - Incl. 21% BTW)');//.toFixed(2)
}
$(document).ready(function(){
$( "#product_configure_form").on("change", ".product-configure-custom-option select", update_amounts);
});
The HTML is pretty long so best is to take a look at the Fiddle.
Can anybody help me to make a correct calculation...?!
Thx in advance
Your conversion from Dutch formatting to normal float formatting is incorrect.
Consider using:
.replace(/[^\d,]/g,"").replace(",",".")
Working example: http://jsfiddle.net/pgaphma3/3/
EDIT
To allow also a plus or minus sign use /[^\d,\-+]/g

Improving speed and data efficiency with javascript calculator.

I'm building a javascript calculator (with jquery mobile) for simplifying routine calculations in microscopy. I'm looking to create more efficient code and would love any input... I don't expect anyone to dig through the whole thing, but here is the link to the program for reference: http://www.iscopecalc.com
(the javascript for the calculator is at http://www.iscopecalc.com/js/calc.js )
The calculator basically consists of about 12 inputs that the user can set. Using the values received from these inputs, the calculator generates values for about 15 different parameters and outputs the results in the display. Currently, whenever the state of an input changes, I bind that change event to a quick function that writes the value for that input to a cookie. But the meat of the program comes with the "updateCalc()" function which reads the values from all of the inputs (from stored cookies) and then recalculates every one of the parameters to be displayed and outputs them. I've coped just that function here for ease of access:
function updateCalc(){
readValues(); //load current calculator state into cookies
var data = $.cookie(); //puts all cookie data into object
var fluorData = fluoroTable[data['fluorophore']]; //fluorophore data taken from table at the end of the file depending on chosen fluorophore
var fluorem = fluorData['fluorem'];
var fluorex = fluorData['fluorex'];
var cameraData = cameraTable[data['camera']]; //camera data taken from table at the end of the file depending on chosen camera
var campix = cameraData['campix'];
var chipWidth = cameraData['chipWidth'];
var chipHeight = cameraData['chipHeight'];
var chipHpix = cameraData['chipHpix'];
var chipVpix = cameraData['chipVpix'];
var RefInd = data['media']; //simple variables taken directly from calculator inputs
var NA = data['NAslider'];
var obj = data['objective'];
var cammag = data['cameraRelay'];
var CSUmag = data['CSUrelay'];
var bin = data['binning'];
var pinholeRad;
var FOVlimit;
var mode;
if (data['modality']=='widefield'){ //FOVlimit, pinholeRad, and CSU mag will all depend on which modality is chosen
FOVlimit = 28;
pinholeRad = NaN;
mode = 'Widefield';
CSUmag = 1;
}
else if (data['modality']=='confocal'){
if (data['CSUmodel']=='X1'){
pinholeRad = 25;
if(data['borealis']=='true'){
mode = "Borealis CSU-X1";
FOVlimit = 9;
}
else {
mode = "Yokogawa CSU-X1";
FOVlimit = 7;
CSUmag = 1;
}
}
else if (data['CSUmodel']=='W1'){
mode = "Yokogawa CSU-W1";
FOVlimit = 16;
pinholeRad = data['W1-disk']/2;
CSUmag = 1;
}
}
//These are main outputs and they depend on the input variables above
var latRes = 0.61 * fluorem / NA;
var axRes = 1.4 * fluorem * RefInd / (NA*NA);
var BPpinhole = 1000 * pinholeRad / (obj * CSUmag);
var AU = BPpinhole / latRes;
var totalMag = obj * cammag * CSUmag;
var BPpixel = 1000 * campix * bin / totalMag;
var samples = latRes / BPpixel;
var pixperpin = BPpinhole * 2 / BPpixel;
var sampLit = 1000 * FOVlimit / (obj * CSUmag);
var coverage = FOVlimit * cammag / chipHeight;
if (coverage < 1) {
chipUsed = coverage;
FOV = sampLit;
}
else {
chipUsed = 1;
FOV = sampLit * chipHeight / (FOVlimit * cammag);
}
var sampWaste = 1 - FOV / sampLit;
var imgpix = 1000 * FOV / (chipVpix / bin);
//function goes on to update display with calculated values...
}
It works ok and I'm generally pleased with the results but here's what I'd like advice on:
Each of the input variables only really affects a handful of the outputs (for instance, a change in input #3 would only really change the calculation for a few of the outputs... not all 15), however, my function recalculates ALL outputs everytime ANY of the inputs are changed, regardless of relevance... I've considered making a giant If-Then function that would selectively update only the outputs that would have changed based on the input that was changed. This would obviously take a larger amount of code, but I'm wondering if (once loaded) the code would be faster when using the calculator, of if it would just be a waste of my time and clutter up my code.
I'm also wondering if storing inputs in cookies and reading values back from cookies is a reasonable way to do things and if I should maybe make a global variable instead that stores the state of the calculator. (the cookies have the added benefit of storing the users calculator state for later visits).
I'm pretty new at this stuff, so any and all comments on how I might improve the efficiency of my code would be greatly appreciated (feel free to just link to a page that I should read, or a method I should be using for instance...)
if you've made it this far, thanks for your time!!

Categories