Addition not working in Javascript - javascript

I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.

That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.

Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.

Try to convert the string to int first with parseInt or to float with parseFloat

This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.

Related

Javascript extract last numbers from Math.random

So I'm trying to do a script for Photoshop with javascript and I can't get the last 6 number from a Math.random.
I tried using the same code as in Strings with "randomID.substr(randomID.length - 6);" or "randomID.substr(-6);" but that didn't work.
var kodi = 'FJ0B';
var randomID = Math.floor(Math.random() * (999999999999 - 100000000000 + 1) + 100000000000);
var lastSix = randomID.toFixed(-6);
var kontrataLayer = (kodi.charAt(0) + lastSix);
Math.floor works fine, I need it with 12 digits for another function.
Thank you.
What about:
var randomIDString = randomID.toString();
var lastSix = Number(randomIDString.substr(randomIDString.length - 6));
For substr to work you need to convert the number to a string. Maybe that's why it didn't work for you earlier?

Type Conversion Issue(?): How to grab html <span> tag's value and perform math on it?

How would I use javascript to take 30% off of the price and then append the discounted price under the old price? I'm getting tripped up on this.
Someone advised that I need to remove the $ some other way...?
HTML
<span class="price">$59.00</span>
JavaScript
var priceOne = parseInt(document.querySelector(".price").innerHTML);
var priceTwo = "$" + priceOne * .70;
document.querySelector(".price").innerHTML = priceTwo;
All tips or advice or solutions is appreciated!
JavaScript isn't able to parse strings to numbers if they have a string in it for whatever reason.
var price = document.getElementsByClassName('price')[0];
price.innerHTML += '<br>$' + (parseFloat(price.innerHTML.replace('$', ''))*0.7).toFixed(2);
<span class="price">$59.00</span>
You can use regular expressions
var priceOne = document.querySelector(".price").innerHTML;
// Use regular expression to strip out all non-numbers
var re = /\.\d+|\d\/\d|\d/g
var result = priceOne.match(re).join('');
//if in the united states, use this, else look on MDN for the correct formatting
document.querySelector(".price").innerHTML = (result*.7).toLocaleString("en-US",{style:"currency",currency:'USD'})
let oriprice = document.getElementById('price').innerHTML;
let priceOne = parseFloat(oriprice.substring(1,oriprice.length));
var priceTwo = "$" + (priceOne * .70).toFixed(2);
console.log(priceTwo)
<span id="price">$59.00 </span>
The problem is that your priceOne was NaN after parsed. Try to use subString to remove the first $ sign, and since it's a decimal amount, instead of using parseInt, use parseFloat and after calculating the 70% of it, apply toFixed on it

get wrong result function jquery javascript

I am using the following script. But I am receiving a wrong result for x_b_bbetrag.
When do an calculation exp 100/108 I get 9.92 instead of 92.59.
What am I missing here?
Code below:
var betrag = 100
var kurs = 1
var minkl= 1
var msatz= 0.08
$("#x_b_betrag").change(function() {
var betrag = $("#x_b_betrag").val();
var kurs = $("#x_b_kurs").val();
var minkl =$("input[name='x_b_mwstinkl']:checked").val();
var msatz =$("input[name='x_b_mwst']:checked").val();
if (minkl == "1"){
$("#x_b_rechenbetrag").val((betrag * kurs).toFixed(2));
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + msatz) ).toFixed(2));
}
Use parseFloat
multiplication, division and subtraction automatically parse string to number. for summation you need to parse it.
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + parseFloat(msatz) ) ).toFixed(2));
///1 + "1" = 11 not 2
Parse your inputs into numbers.
For example :
var betrag = parseFloat($("#x_b_betrag").val());
MDN on parseFloat
The value of the msatz variable is not 0.08 but "0.08". It's a string, so when you add one to it, the number will be converted to a string so that they can be concatenated, and the result is "10.08" not 1.08. The string will implicitly be converted to a number when you use it in the division, as it's not possible to divide by a string.
Parse the string into a number:
var msatz = parseFloat($("input[name='x_b_mwst']:checked").val());

Adding User input without rounding (Google Apps Script)

I am adding a users input in to UI as they add numbers and returning the results. The input is currency so I need to carry it out two decimals and not round.
Here is an example of my code:
function ceiling2(number) {
var ceiling2;
return ceiling2 = Math.ceil(number*100)/100;
}
//Totals
function lD23Total (e){
var app = UiApp.getActiveApplication();
var tB1v = parseInt(e.parameter.TextBox1);
var tB9v = parseInt(e.parameter.TextBox9);
var tB17v = parseInt(e.parameter.TextBox17);
var tB25v = parseInt(e.parameter.TextBox25);
var tB33v = parseInt(e.parameter.TextBox33);
var tB41v = parseInt(e.parameter.TextBox41);
var tB49v = parseInt(e.parameter.TextBox49);
var lD23 = app.getElementById("LabelD23").setStyleAttribute('fontWeight','bold');
var lD23T = tB1v + tB9v + tB17v + tB25v + tB33v + tB41v + tB49v;
lD23.setText("$ " + ceiling2(lD23T));
var app = UiApp.getActiveApplication();
app.close();
return app;
}
Currently it returns a rounded number.
I appreciate an suggestions you may offer!
Jon
The function parseInt() will convert the value to an integer, dropping the values after the decimal. Use parseFloat() instead.
I think your function is just fine...
if you remove the parseInt() and replace it either with parseFloat()as suggested by Eric or by Number() it should work...
if not then the problem might come from the way numbers are written:
If you used 26,4567 but you should use 26.4567 with a dot as separator in place of a comma.
Could you try and keep us informed ?
regards,
Serge
Or you can use this before sending to your function:
var newnumber=Number(number.toString().replace(",","."));// convert to string, replace comma with dot and set as number again.
and your function will work in both cases

jQuery / javascript variable in if statement not working

I have a variable as such:
var is_last = $('.paging a:last').attr('rel');
this returns '-400' which is correct.
However, i need to add 200 to this so the answer is '-200'
if i do this:
var is_last = $('.paging a:last').attr('rel')+200;
the variable is now '-400200'
How can i pass the variable as a value?
A.
You need to parse the output of .attr(), it to an integer first using parseInt() so you're dealing with a number (and not a string), like this:
var is_last = parseInt($('.paging a:last').attr('rel'), 10) + 200;
I reckon that #Nick Craver is correct and that parseInt is the more correct answer, but as a quick-and-dirty alternative you can also convince javascript that a variable is a number and not a string by multiplying by 1:
var x = parseInt("-400", 10) + 200;
var y = ("-400" * 1) + 200;
alert(x);
alert(y);

Categories

Resources