Why error ?
expected results = 1360000
result = 1000000360000
<script>
function hitungJumlah() {
var jumlah = document.getElementById("pinjam").value;
var lama = document.getElementById("kembalinya").value;
var bunga = lama * 12/100;
var biaya = document.getElementById("biaya").value = jumlah * bunga;
document.getElementById("total").value = jumlah + biaya;
}
</script>
Because it's read your data as string use parseInt() function to make your data as Integer
Try with this
parseInt(jumlah) + parseInt(biaya)
Beacuse 1000000 and 360000 act as string . + is also used for concatination in javascript
Because the * operator wont type coerce like + operator. Besides you may not have to use document.getElementById() all the time. You might simply do;
<script>
function hitungJumlah() {
var jumlah = Number(pinjam.value),
lama = Number(kembalinya.value),
bunga = lama * 12/100;
biaya.value = jumlah * bunga;
total.value = jumlah + biaya;
}
</script>
Though parseInt() and Number() have differences. While parseInt("42*10") would result 42, as a number object constructor Number("42*10") would result a NaN.
So be careful playing with them.
Related
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}`)
Into a JQuery script I have the following problem trying to use the toFix() JavaScript method on a number.
So I have the following situation:
var anticipoProgetto = $("#valoreAnticipo").text();
var saldoProgetto = $("#valoreSaldo").text();
var anticipoCalcolato = (saldoProgetto + anticipoProgetto);
console.log("ANTICIPO CALCOLATO: " + anticipoCalcolato);
anticipoCalcolato = anticipoCalcolato.toFixed(2);
$("#anticipoModaleUlterioreSaldo").val(anticipoCalcolato);
The console.log() show:
ANTICIPO CALCOLATO: 2192.002200.37
So it means that JavaScript have correctly perform the addition.
The problem is that wehn try to perorm this line to obtain a value with only 2 decimals digits:
anticipoCalcolato = anticipoCalcolato.toFixed(2);
in the FireBug console I obtain this messagge error:
TypeError: anticipoCalcolato.toFixed is not a function
anticipoCalcolato = anticipoCalcolato.toFixed(2);
Why? What am I missing? How can I fix this issue?
The math is wrong because you are adding two string together, not two numbers. And he toFixed error is because you are trying to use toFixed on a string, but that ethod only exists on numbers.
Convert the strings to numbers when you read the .text()
var anticipoProgetto = parseFloat($("#valoreAnticipo").text()),
saldoProgetto = parseFloat($("#valoreSaldo").text()),
anticipoCalcolato = anticipoProgetto + saldoProgetto,
fixed = anticipoCalcolato.toFixed(2);
#espacarello is correct, you need to cast from string to number. It may be more to your intent to cast them as you read them.
If #valoreAnticipo is an input element, consider switching to .val() instead of .text()
var anticipoProgetto = parseFloat($("#valoreAnticipo").text()) || 0;
var saldoProgetto = parseFloat($("#valoreSaldo").text()) || 0;
var anticipoCalcolato = (saldoProgetto + anticipoProgetto);
console.log("ANTICIPO CALCOLATO: " + anticipoCalcolato);
anticipoCalcolato = anticipoCalcolato.toFixed(2);
$("#anticipoModaleUlterioreSaldo").val(anticipoCalcolato);
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());
Can anyone help me figure out why I keep getting a NaN result?
function showShares() {
var tot = document.getElementById('total').innerHTML;
var pri = document.getElementById('price').innerHTML;
var per = document.getElementById('percent').innerHTML;
var shar = parseInt(tot, 10) * parseFloat(per) / parseFloat(pri);
document.getElementById("shares").innerHTML=Math.round(shar);
}
<td><text id="price"><%= StockQuote::Stock.quote(current_user.fund1).last %></text></td>
<td><text id="shares"></text></td>
<td><text id="percent">.50</text></td>
<p class="alignright1"><input type="text" id="total" size="8"></input>
<br><a href onclick="showShares()">here</a>
The stock quote is returning an integer in the cell ie. 25.38. it returns the same NaN if I remove the embedded ruby and place a simple integer ie. 50. The same is true if I replace the input with a number.
Thank You
Try this :
function showShares() {
var tot = document.getElementById('total').innerHTML;
var pri = document.getElementById('price').innerHTML;
var per = document.getElementById('percent').innerHTML;
var shar = parseInt(tot, 10) * parseFloat(per, 10) / parseInt(pri, 10);
document.getElementById("shares").innerHTML=Math.round(shar);
}
The percent value is a float (digit with comma) and must be interpreted by the JS engine like a float ;)
You are trying to get a value from an input element with this code,
document.getElementById('total').innerHTML
That's not the way to get the value from the input. You should use this code,
document.getElementById('total').value
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.