get wrong result function jquery javascript - 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());

Related

Sum of toFixed not working correctly

I have the following code that calculates and shows the sum of two values.
var oldprice_formated = parseFloat(oldprice).toFixed(2);
var extraPrice = parseFloat(3).toFixed(2);
if(initials != '') {
var new_price = oldprice_formated + extraPrice;
$('.product-detail .woocommerce-Price-amount.amount').html('<span>€</span>'+new_price);
} else {
$('.product-detail .woocommerce-Price amount.amount').html('<span>€</span>'+oldprice_formated);
}
For example:
oldprice_formated = parseFloat(49.99).toFixed(2);
extraPrice = parseFloat(3.00).toFixed(2)
The expected result: Sum is 52.99
Actual result: Sum is 49.003.00
What am I doing wrong? I assume it's with the number parsing, but not sure what I should change to make it work correctly. Thanks!
.toFixed() returns a string, not a number with only two decimal places.
oldprice_formated = parseFloat(49.99).toFixed(2); // "49.99"
extraPrice = parseFloat(3.00).toFixed(2); // "3.00"
When adding those two variables, instead of a number sum, you're concatenating two strings:
"49.99" + "3.00"; // "49.993.00"
I believe this is what you'll want to do:
var new_price = parseFloat(oldprice_formated) + parseFloat(extraPrice);
Or simply run .toFixed() after you sum those values which were already parsed to floats.
Because toFixed() returns a string, the + operator acts as a string concatenator. If you want it to operate as an addition operator, you must typecast your values as numbers:
let oldprice = 49.99;
let oldprice_formatted = parseFloat(oldprice).toFixed(2);
let extraPrice = parseFloat(3).toFixed(2);
console.log(`string concatenation: ${oldprice_formatted + extraPrice}`)
console.log(`type conversion: ${+oldprice_formatted + +extraPrice}`)

Regarding decimal in javascript

When i am writing 11.00 it is displaying 11.00.00 otherwise its working fine on rest
if(pos == -1)
{
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount + ".00";
}
else
{
var integer = enterCheckAmount.substring(0,pos);
var decimals = enterCheckAmount.substring(pos+1);
while(decimals.length<2) decimals=decimals+'0';
enterCheckAmount = integer + '.' + decimals;
document.getElementById("printCheckAmount").textContent = "$" + checkObj.checkAmount;
}
JavaScript doesn't have a variable type for decimal numbers. It has only Number. If you want to display an integer as a decimal number with two zeros after the decimal point you can use the method toFixed.
Here is an example:
var myNumber = 11;
var myDecimalNumber = myNumber.toFixed(2);
console.log(myDecimalNumber) // will output 11.00
Thus there is no need to concatenate strings and add ".00" manually to your number.
Beyond this you can use the methods parseInt and parseFloat. Let's say you have a variable of type string with the value "11 pieces". You can get the integer with this line of code:
var myString = "11 pieces";
var myInteger = parseInt(myString, 10);
console.log(myInteger); // will output 11
If you have something similar like this, you are better off with this methods instead of cuting substrings.
I wish you a lot of success in refactoring your code and a warm welcome to the StackOverflow community.

Addition not working in 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.

Summing variables with parseInt(); Not Working

What is the proper way to add the sum of multiple variables in Javascript?
This is what I'm trying to do. I've tried it with and without the quotes around my variables. I'm not getting a NaN or an Undefined or anything. No output whatsoever.
function setstat(){
document.getElementById('date').value = window.opener.document.getElementById('thisday').value;
document.getElementById('name').value = window.opener.document.getElementById('element_7').value;
document.getElementById('time').value = window.opener.document.getElementById('stwa').value;
inbcalls = window.opener.document.getElementById('element_6').value;
document.getElementById('totinb').value = inbcalls;
inbcallsp = parseInt("inbcalls",10);
asaptotal = window.opener.document.getElementById('asapcalls').value;
document.getElementById('asaptot').value = asaptotal;
asaptotalp = parseInt("asaptotal",10);
faxtotal = window.opener.document.getElementById('faxcalls').value;
document.getElementById('faxtot').value = faxtotal;
faxtotalp = parseInt("faxtotal",10);
obtotal = window.opener.document.getElementById('obcalls').value;
document.getElementById('obtot').value = obtotal;
totalcalls = inboundcallsp + asaptotalp + faxtotalp + obtotalp;
document.getElementById('totsum').value = totalcalls;
}
Why are you quoting the variable names?
inbcallsp = parseInt("inbcalls",10);
should be:
inbcallsp = parseInt(inbcalls, 10);
And the same for the rest of them. You want to parse the value of the variables, not the names of the variables; those will always result in NaN.
asaptotalp = parseInt("asaptotal",10);
"asaptotal" is recognize as the string not the variable
you should not quote it
When using parseInt always specify the radix as 10.
The function singnature: parseInt(string, radix)
The radix is optional but if ommited, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
Example:
parseIn("05") ==== 0 -> true
parseIn("05", 10) ==== 5 -> true
Don't use ParseInt, sometimes it will not return the proper value.
Better use Number, for example:
var i=Number(your value)

Convert String to Float in Javascript error

Please see below code,i getting wrong value.
eg;
var FirstValue=0.00;
var secondvalue=parseFloat("22.88",10).toFixed(2);
var thirdvalue=(FirstValue) + (secondvalue);
am getting value like"22.8822.88"
Please help me to solve.Its not convert to numeric .
toFixed convert you float value to string back. So when you adding two values you will get not number addition but string concatenation:
2.0 + 2.0 = 4.0 // number
"2.0" + "2.0" = "2.02.0" // string
Remove to fixed after conversion. Than add two values and than do to fixed:
var FirstValue=0.00;
var secondvalue=parseFloat("22.88",10);
var thirdvalue= ( (FirstValue) + (secondvalue) ).toFixed(2);
try this:
var FirstValue=0.00;
var secondvalue=parseFloat("22.88");
secondvalue = parseFloat(secondvalue.toFixed(2));
var thirdvalue=(FirstValue) + (secondvalue);
toFixed returns a string, not a number so it needs to be converted again.

Categories

Resources