Javascript .val() issue - javascript

When I enter a decimal for chance, it returns NaN for pay and profit. Any idea why? Also what would I need to do to round profit to the second decimal.
Thanks.
$(document).ready(function(){
function updateValues() {
// Grab all the value just incase they're needed.
var chance = $('#chance').val();
var bet = $('#bet').val();
var pay = $('#pay').val();
var profit = $('#profit').val();
// Calculate the new payout.
var remainder = 101 - chance;
pay = Math.floor((992/(chance+0.5)) *100)/100;
// Calculate the new profit.
profit = bet*pay-bet;
// Set the new input values.
$('#chance').val(chance);
$('#bet').val(bet);
$('#pay').val(pay);
$('#profit').val(profit);
}
$('#chance').keyup(updateValues);
$('#bet').keyup(updateValues);
$('#pay').keyup(updateValues);
$('#profit').keyup(updateValues);
});

First make use of parseFloat or (parseInt if you don't need float values).
function updateValues() {
var chance = parseFloat($('#chance').val());
var bet = parseFloat($('#bet').val());
var pay = parseFloat($('#pay').val());
var profit = parseFloat($('#profit').val());
// Calculate the new payout.
var remainder = 101 - chance;
pay = Math.floor((992/(chance+0.5)) *100)/100;
}
Also what would I need to do to round profit to the second decimal.
you can do this:
profit = bet*pay-bet;
profit = profit.toFixed(2);

You need to use parseFloat to properly work with the values, which by default are strings:
var chance = parseFloat($('#pay').val());
/*same for other values*/
To round the profit to 2 decimals, you can use toFixed on that number, which again converts it back to a string.
3.123.toFixed(2) = "3.12"

Try using parseFloat:
var chance = parseFloat($("#Chance").val());
You can also use toFixed to specify the number of decimal places.
Edit
You need to modify chance:
chance = parseFloat(chance);
You can see this working here:
http://jsfiddle.net/U8bpX/

Related

jQuery removing numbers after the point

I would like my result to show the whole number as 1500, not 1500.00. I tried round () and toFixed () but it doesn't change my result and it doesn't round. Where do I go wrong?
var applying_credit_final = "applying_credit";
var applying_credit = thisPointer.entity['applying_credit'];
applying_credit_final = parseFloat(applying_credit_final);
applying_credit = parseFloat(applying_credit);
if (!isNaN(applying_credit_final) && !isNaN(applying_credit)) {
var resultUNi = Number((applying_credit / 1000).toFixed())
var numeralValUni = numeral(resultUNi)._value;
numeralValUnit.toFixed()
My source
https://jsfiddle.net/Palucci92/jueL50hb/4/
To remove excessive decimals you need to specify the number of digits to keep as parameter on toFixed:
var resultUNi = Number((applying_credit / 1000).toFixed(0))
Notice 0 as parameter in toFixed(0) resulting in an integer. You can also leave the parameter out if its zero because it defaults to it.

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.

JavaScript parseFloat() issue

Okay so my code works fine but when a decimal i.e. 60.1, 60.2, 60.3, etc. is input for #chance it screws up profit and pay.
For example: 60% is input for chance, 1 for bet. It returns 1.65 for pay and 0.65 for profit. That's all correct.
But when I put 60.1, it returns 16.5 ( wrong decimal ) and 15.5 for profit. 16.5 seems like an easy fix but Idk how to fix it, but I have no idea why it's returning 15.5 for profit and thought maybe if I fixed pay it would fix the issue with profit.
What's wrong?
Thanks.
<script>
$(document).ready(function(){
function updateValues() {
// Grab all the value just incase they're needed.
var chance = $('#chance').val();
var bet = $('#bet').val();
var pay = $('#pay').val();
var profit = $('#profit').val();
// Calculate the new payout.
var remainder = 101 - chance;
pay = Math.floor((992/parseFloat((chance+0.5))) *100)/100;
// Calculate the new profit.
profit = bet*pay-bet;
profit = profit.toFixed(6);
// Set the new input values.
$('#chance').val(chance);
$('#bet').val(bet);
$('#pay').val(pay);
$('#profit').val(profit);
}
parseInt($('#chance').keyup(updateValues));
parseInt($('#bet').keyup(updateValues));
parseInt($('#pay').keyup(updateValues));
parseInt($('#profit').keyup(updateValues));
});
</script>
parseFloat((chance+0.5))
looks very wrong. chance is a string, so the + operator will perform string concatenation. When you input 60, it becomes
parseFloat("60"+0.5) === 600.5
while when you input 60.1 it is
parseFloat("60.1"+0.5) === 60.1
You probably wanted
(992/(parseFloat(chance)+0.5))*100
// or
(992/parseFloat(chance)+0.5)*100
// or
992/parseFloat(chance)*100+0.5
// or something along these lines
Change parseFloat((chance+0.5)) into (parseFloat(chance)+0.5).
Actually, I can't see why it's working with 60, either. chance, as a value of a text field, is a string: "60". Strings don't add, they concatenate: "60" + 0.5 is "600.5", same as "60" + "0.5".
Try something like this:
$(document).ready(function(){
function updateValues(){
var chance = $('#chance').val();
var bet = $('#bet').val();
var pay = $('#pay').val();
var profit = $('#profit').val();
pay = ((992/Math.floor(+chance+0.5))/10).toFixed(2);
profit = (bet*pay-bet).toFixed(6);
$('#chance').val(chance);
$('#bet').val(bet);
$('#pay').val(pay);
$('#profit').val(profit);
}
$('#chance').keyup(updateValues);
$('#bet').keyup(updateValues);
$('#pay').keyup(updateValues);
$('#profit').keyup(updateValues);
});
Something is wrong with your Math.
Note:
You don't have to use parseInt() or parseFloat() to make Strings to Numbers. the + symbol in front of your String that is a Number will convert it to a Number.
See http://jsfiddle.net/PHPglue/JQJMD/ for more details.

jQuery/Javascript splitting string calculation

I'm creating a product page that requires the price to update when the quantity value is changed. Two form fields are used: .orig_price and #quantity. These values are obviously multiplied together.
I'm trying to split the multiplied value, so that I can print the correct format (27.7043454575 should be 27.70).
My code:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = jQuery(".orig_price").val().substr(1);
var qty = jQuery("#quantity").val();
// calculate price
var sumValue = origprice * qty;
// split price
var splitprice = sumValue.split(".");
var pricepound = splitprice[0];
var pricepenny = splitprice[1].substring(0,2);
// update price
jQuery("#pricediv").html('£' + pricepound + '.' + pricepenny);
jQuery("#pricediv").fadeIn(1500);
});
If I remove the split and use sumValue everything works (but format is wrong). Does split not work on a calculation?
You'll want to use sumValue.toFixed(2)
var sumValue = 27.7043454575;
sumValue.toFixed(2) // 27.70
.split does not exist on numeric types. You would have to use sumValue.toString().split('.'), and either way, this would be more inconvenient than simply sticking to .toFixed
You can use toFixed and parseInt() like so:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = parseInt(jQuery(".orig_price").val().substr(1),10);
var qty = parseInt(jQuery("#quantity").val(),10);
// calculate price
var sumValue = origprice * qty;
// split price
var price = sumValue.toFixed(2);
// update price
jQuery("#pricediv").html('£' + price);
jQuery("#pricediv").fadeIn(1500);
});
toFixed determines the number of points after a decimal, and parseInt type-casts the input to an integer (the 10 is unnecessary but there to show it's decimal base 10), because when getting data from a form field it sometimes comes back as a string and messes up your math.

simple calculation of integer and decimal number in jquery

Trying to multiply 2 values. Quantity is integer and credit price is decimal number. When I run this code nothing happens.
Does anyone know what is the issue?
Thank you.
$(function(){ // bind the recalc function to the quantity fields
$("#oneCreditSum").after('<label></label>Total: Aud <span id=\"total\"></span><br><br>');
$("#quantity").bind('keyup', recalc);
function recalc(){
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = quantity * creditPrice;
$("#total").text(total);
}});
Use parseFloat on the values, and alert each one individually to test.
A few other (unrelated) improvements:
Use keyup() function:
$("#quantity").keyup(recalc);
Make function anonymous:
$("#quantity").keyup(function(){...});
Use $(this) on #quantity in the function to avoid calling the jQuery selector again
You could also consider condensing this into a single line of code:
$("#total").text(parseFloat($('#quantity').val()) * parseFloat($('#creditPrice').val()));
To zero-pad you might try something toFixed():
var num = 10;
var result = num.toFixed(2); // result will equal 10.00
I got this snippet from the following site
http://www.mredkj.com/javascript/numberFormat.html
Hope this helps.
use
parseFloat
before calculation on both numbers which parses a string argument and returns a floating point number.
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = parseFloat(quantity) * parseFloat(creditPrice);
If you are interested in whole number only you can use this function instead:
parseInt

Categories

Resources