JavaScript parseFloat() issue - javascript

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.

Related

JavaScript operator + doesn't work normally

Need some help with this simple code, if we will input the value for "work experience" for example 3 and the salary "1000" by the condition the salary should add 10% to the initial salary so the result should be "1100" but in my formula it shows the result like 1000250, i observed if i change the symbol "+" into "-" it shows correctly "900", what i am doing wrong?
if (age>=3 && age<10) {
var increase_1;
var salary_2;
increase_1=(salary*10)/100;
salary_2=salary+increase_1;
document.write('<h4>' +'Proceeding from work experience the new salary was increase by 10%:\t'+ +salary_2+ '<\h4>');
Also if i am using the salary a defended value like "salary=1000;" the program works with no problem.. waiting for some answers, thx
<html>
<head>
</head>
<script>
function doStuff()
{
var nameAge = document.getElementById("ageInput");
var age = nameAge.value;
var nameSalary = document.getElementById("salaryInput");
var salary = nameSalary.value;
document.write('<h2>' +'Age experience:\t'+ +age+ '<\h2>');
document.write('<h2>' +'Starting salary ($):\t'+ +salary+ '<\h2>');
if (age>=3 && age<10) {
var increase_1;
var salary_2;
increase_1=(salary*10)/100;
salary_2=salary+increase_1;
document.write('<h4>' +'Proceeding from work experience the new salary was increase by 10%:\t'+ +salary_2+ '<\h4>');
}
else if (age>=10 && age<20){
var increase_2;
var salary_3;
increase_2=(salary*25)/100;
salary_3=salary+increase_2;
document.write('<h4>' +'Proceeding from work experience the new salary was increase by 25%:\t'+ +salary_3+ '<\h4>');
}
else if (age>=20){
document.write('<h4>' +'Proceeding from work experience you get a prize:'+ '<\h4>');
document.write('<img src="http://3.bp.blogspot.com/-2T_AGEs19_4/T_c2ERHsJeI/AAAAAAAIK9E/MGAQAa9ppDE/s800/2013-Mercedes-G-Class-AMG-011.jpg">');
}
else {
document.write('<h4>' +'Proceeding from work experience the salary is:\t' +salary+'<\h4>');
}
}
</script>
<h1>Please enter your work experience(years)</h1>
<input id="ageInput" type="text">
<h1>Please enter your salary($)</h1>
<input id="salaryInput" type="text">
<input type="button" value="Submit" onClick="doStuff()">
</html>
JavaScript is seeing some values which are taken from input boxes as strings of text rather than numeric values, and simple concatenating them.
If you are reading a value from a input box and want to use it in an equation, you need to run it though parseInt() first. e.g.
var age = parseInt(nameAge.value, 10);
Or if you want to use decimal values (floats) you need to run it through parseFloat()
var salary = parseFloat(nameSalary.value);
Passing the radix (10) as the second parameter to parseInt() will prevent older browsers which use ECMAScript less than version 5 from interpreting numbers starting with a 0 as octal values.
Parse your input to an int (or a float if you want decimals!), it's reading as a string, thus concatenating.
var salary = parseInt(nameSalary.value);
var age = parseInt(nameAge.value);
To get a numeric from a form field, you have to get it converted to a number, the quickest way to do that is to subtract zero from that variable.
salary-=0;
increase_1=salary+((salary*10)/100);
salary_2=salary+increase_1;
Your salary of "1000" will result in an (int)1000 that is then *10 = 10000 then /100 = 100 and added to the original sum of 1000 to make 1100.
You could try using a function or a prototype to do the leg work for you,
Number.prototype.percent = function(p){
return ((this-0)*p)/100;
}
then you can simply... increase_1=salary+(salary.percent(10));

Javascript .val() issue

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/

jquery: percentage of two numbers (Part 2)

this is continuation of last successful topic
jquery: percentage of two numbers
First of all I want to thank you for your prompt support of previuous post.
Now I would like to make my script a little bit more complicated. I want to achive the following: If I insert PRICE1 and PRICE2 to have RATE between THEM, then I can change the RATE with other value and PRICE2 to change to the corespondent value according to RATE value.
My script of calculation is close to be correct, but my low knowledge about JQuery make me to ask you where I do something wrong.
Thank you for your support!
<script src="libs/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#PRICE1, #PRICE2").change(function() {
var result = parseFloat(parseFloat($("#PRICE1").val(), 10) - parseFloat($("#PRICE1").val(), 10))/ parseFloat($("#PRICE2").val(), 10) * 100;
$('#RATE').val(result||'');
})
else {
$("#PRICE1, #RATE").change(function() {
var result = parseFloat(parseFloat($("#PRICE1").val(), 10) * parseFloat($("#RATE").val(), 10))/ 100 + parseFloat($("#PRICE1").val(), 10);
$('#PRICE2').val(result||'');
})}
});
</script>
EDITED:
THE CODE ALMOST WORKING CORRECTLY WHICH MIGHT HELP OTHERS:
$(document).ready(function(){
$("#priceOne, #priceTwo").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var priceTwo = parseFloat($("#priceTwo").val());
$('#Rate').val((priceTwo - priceOne) / priceOne * 100); // Set the rate
});
// If price one or the rate is changed, adjust price two.
$("#priceOne, #RATE").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var rate = parseFloat($("#Rate").val());
$('#priceTwo').val((priceOne * rate)/ 100 + priceOne);
});
})
Thank you everyone who help me!!!
There is a else and no matching if. I'm not sure what you're trying to achieve, but some condition needs to be checked.
I'm going to try and code what it appears you need. But I'm going to rename your variables, not only because allcaps are hard to type, but unless it's a constant or a macro, they shouldn't be used.
// In ready() callback
// #NOTE - This does NO error checking for division by 0 or other NaN operations.
// If price two is changed, adjust the rate.
$("#priceTwo").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var priceTwo = parseFloat($(this).val());
$("#rate").val(priceTwo / priceOne); // Set the rate
});
// If price one or the rate is changed, adjust price two.
$("#rate #priceOne").change(function() {
var priceOne = parseFloat($("#priceOne").val());
var rate = parseFloat($("#rate").val());
$("#priceTwo").val(priceOne * rate);
});
There are a few things about your code that needs attention:
parseFloat doesn't take a radix argument, the 10 you pass it is ignored.
parseFloat(parseFloat(... is pointless, I'm not sure why you've done this.
Don't use jQuery to select the same element multiple times in the same scope. Save the value and re-use it - save yourself some cycles.
As I mentioned, don't name your variables in all capitals unless they are some sort of constant that should never be changed, it's good to have clean style habits.

Adding a 0 before decimal entered in input?

I'm attempting to finish up a quick form using jQuery that needs to add a 0 before a decimal point if the decimal is the first char entered in the input.
For example,
.25 would become 0.25 before the form is submitted.
However, 2.05 would stay as 2.05, and no 0 would be added.
Is there a simple function here that could help me out? I'd rather not write something long and detailed if it's not necessary.
Also, here is the input box that I am asking for help with, for reference
<input type="number" name="dailygain" id="dailygain" />
You can use parseFloat function to format float numbers.
var el = document.getElementById("dailygain");
el.value = parseFloat(el.value);
Multiply by 1 (*1) to make it numeric.
If you make it a number, it'll do it for you automatically; formatting based on your systems locale.
Example:
var x = '.25';
console.log( x*1 ); // 0.25
The same can be accomplished with a unary plus (e.g., console.log( +x ); )
Put this in a function run onsubmit.
var num=$("#dailygain").val(); //read the number from the textbox
num=num.toString(); //convert that number to a string
if (num.charAt(0)==".") //check if the string starts with a period
num="0"+num; //if so, add a 0 in front of it
$("#dailygain").val(num); //write the number back to the tb
parseFloat is probably more suited, but anyway :
$('#dailygain').on('keyup', function() {
if (this.value[0] === '.') this.value = '0'+this.value;
});
FIDDLE
​
$("input[name=dailygain]").keyup(function(){
var val = this.value;
if(val.charAt(0) === '.'){
this.value = ('0'+val);
}
});
http://jsbin.com/ofivun/2/edit

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