I have an odd issue that I'm not sure quite how to fix, but here it goes.
I've got a return from an AJAX query and this is how two parts are returned (and how they look in the preview panel):
id:1
paid: "158.40"
balance: "79.20"
So initially I had just tried the following (after noticing an issue):
if(item.balance > item.paid){
var test = "balance greater than paid";
}else{
var test = "balance is not";
}
But in the above case, it returns the first test meaning that somewhere, the it thinks that 79.20 is greater than 158.40, which is obviously not what I want.
So I tried this:
var paid = parseFloat(item.paid).toFixed(2);
var balance = parseFloat(item.balance).toFixed(2);
And just switch the first line of the above conditional statement to if(balance > paid) and it still did the same thing...
So I am at a loss, if anyone can help - I'd be very appreciative.
Don't use toFixed when comparing those values, because it just gives you another string, which it can't compare numerically in the way you're trying to compare. Just compare the outputs of parseFloat.
var paid = "158.40";
var balance = "79.20";
$(".string").text(paid > balance);
paid = parseFloat("158.40");
balance = parseFloat("79.20");
$(".float").text(paid > balance);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
String compare:
<span class="string">
</span>
</div>
<div>
Float compare:
<span class="float">
</span>
</div>
try to use Number() to convert string to numbers first
if(Number(item.balance) > Number(item.paid)){
var test = "balance greater than paid";
}else{
var test = "balance is not";
}
Use it like below
var paid = parseFloat(item.paid);
var balance = parseFloat(item.balance);
Then compare it will take you into right condition
Above you are using toFixed which again returns string.
Referring to toFixed method, it is returning a String, not a Number. Hence the comparison result is not expected. There is no need to call this method for your case. If you have concern on the precision, take a look on this question
var item = {
id: 1,
paid: "158.40",
balance: "79.20"
};
var paid = parseFloat(item.paid);
var balance = parseFloat(item.balance);
console.log("paid=" + paid);
console.log("balance=" + balance);
console.log("paid>balance=" + (paid > balance));
Related
I'm trying to do what I thought was pretty straight forward but having odd results. I have two fields on a page: transactionAmount and transactionLimit. When the button is clicked, it calls a javascript function that makes sure the amount isn't greater than the limit:
var transactionAmount = parseFloat(document.getElementById("amount").value).toFixed(2);
var transactionLimit = parseFloat(document.getElementById("limit").value).toFixed(2);
if (transactionAmount > transactionLimit) {
alert("Over limit");
}
If I set the transactionAmount to be $2.00 and the transaction Limit to be $100.00, I get the over limit alert. If I set the transactionAmount to be $1.00 then it works fine. Basically any other value less than $1.00 works if the limit is $100.00 but anything over $1.00 gives me the error.
Would be grateful for some insight! Thank you!
The main problem happening because of toFixed(2) it converts your result to string that's why your condition is not working as you expected. just wrap it with preceding + character to make it Number from String
var transactionAmount = +(parseFloat('2.00').toFixed(2));
var transactionLimit = +(parseFloat('100.00').toFixed(2));
console.log(transactionAmount,transactionLimit, typeof transactionAmount,typeof transactionLimit )
if (transactionAmount > transactionAmount ) {
console.log("Over limit");
}
Try to add the function "Number()" to you values, toFixed() actually transform them to string. You can also add a "+" before to do the same action.
Example:
var transactionAmount = Number(parseFloat("150.00").toFixed(2)); //or: +parseFloat("150.00").toFixed(2)
var transactionLimit = Number(parseFloat("100.0").toFixed(2)); //or: +parseFloat("100.0").toFixed(2)
if (transactionAmount > transactionLimit)
{
alert("Over limit");
} else {
alert("you ok dude");
}
Output:
"Over limit"
I hope it helps you!
I am working on javascript code that parses a tab delimited document. In order to facilitate searching I need to convert those properties that are a number to a float. However, mixed fields (like an address) should maintain the status of a String.
for(var i2=0;i2<line1.length;i2++){
var test = local[i2];
if(! (typeof test === 'undefined')){
test = test.trim();
};
var parsed = parseFloat(test);
if(!isNaN(parsed)){
if(line1[i2] === "Site Address")
console.log("Number before:"+local[i2]+" After:"+parsed);
object[line1[i2]]=parsed;
}
else{
if(line1[i2] === "Site Address")
console.log("before:"+local[i2]+" After:"+test);
object[line1[i2]]=test;
}
}
This seems to work ok unless there are both numbers and chars like the following....
Number before:1752 E MAIN ST After:1752
Is there a way to do this where the above is not seen as explicitly a number?
You can use the unary + operator:
var parsed = +test;
The parseFloat() function is OK with strings that start with a valid number that's followed by non-numeric stuff, as you've discovered.
If that seems too "hackery" you can also use the Number constructor:
var parsed = Number( test );
You haven't provided very much test data, so answers may not be very good. You can try using a regular expression so that only things that look like numbers are treated as numbers, e.g.
var isNum = /^\d+(\.\d+)?$/;
var test = line1[i2];
parsed = isNum.test(test)? parseFloat(test) : test;
The variable "test" would probaby be better named "item" or "value" or similar.
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));
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.
Been out of the regex game for a while. Trying to come up with something that will allow the user to enter a money value either with/without dollar sign or with/without commas. For example, all the of the following values should be valid:
5
5.1
5.10
$5
500,000
500,000.1
500,000.10
$100,000,000.50
etc....
Could someone please help me out?
This should work:
isValid = str.search(/^\$?[\d,]+(\.\d*)?$/) >= 0;
A little more strict with comma placement (would reject 3,2.10, for example):
isValid = str.search(/^\$?\d+(,\d{3})*(\.\d*)?$/) >= 0;
To get a number out of it:
if(isValid) {
var num = Number(str.replace(/[\$,]/g, ''));
...
}
I didn't Test Driven Developement, TDD, for this one using the Qunit framework.
TDD overview http://net.tutsplus.com/tutorials/javascript-ajax/test-driven-javascript-development-in-practice/
1st: Write tests.
2nd: Watch tests fail.
3rd: Make test pass.
4th: Refactor.
var moneyTest_RE = /^\$?\d+((,\d{3})+)?(\.\d+)?$/;
test("test money format for valid values", function () {
var moneyArr = ["5","5.1","5.10","$5","500,000","500,000.1","500,000.10","$100,000,000.50", "500,000,100" ];
var i = moneyArr.length;
while( i-- ){
equal( moneyTest_RE.test( moneyArr[ i ] ), true, moneyArr[ i ] + " didn't match completely." );
}
});
test("test money format for invalid values", function () {
var moneyArr = ["5..","$$5.1",".5.10","$5.2.","50,0,000",",500,000.1","500,000,10,","$1,00,000,000.50", "500,000,10"];
var i = moneyArr.length;
while( i-- ){
equal( moneyTest_RE.test( moneyArr[ i ] ), false, moneyArr[ i ] + " didn't match completely." );
}
});
Here's one possible solution to your problem.
var moneyTest_RE = /^\$?\d+((,\d{3})+)?(\.\d+)?$/;
Demo here: http://jsfiddle.net/vpyV6/
I forgot to refactor though.
^(\$?\d{1,3}(?:,?\d{3})*(?:\.\d{2})?|\.\d{2})?$
This one took a while, but I finally got something fully functional. It allows for cases such as 100.00, .35, $1.35, etc. While excluding entries with misplaced commas, too many numbers in between or before commas, or too many numbers after the decimal point.
You can play around with it here
var currencyRegex = /^[$£€]\d+(?:\.\d\d)*$/g;
Example: $10 or £10 0r €10 but if you use simple 10 this will be wrong
Perhaps this?
http://refiddle.com/2tg
(\$?(:?\d+,?.?)+)
Also, http://refiddle.com/2ti ; a longer version that doesn't match numbers like 123,45.4.3
^(\$?(:?\d+,?)+(?:.?\d+)?)$