Javascript Floating Number Comparison - javascript

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!

Related

Searching keywords in JavaScript

Here's an example of the customer codes:
C000000123
C000000456
If I input C123 in the search box, "C000000123" will automatically display.
9 numbers are fixed.
Please help me, a short sample was shown to me but I don't get it.
function test(key, num, digit) {
let retStr;
xxxx (condition)
retun retStr;
}
here's an elaboration:
**
input:123
output:A00000123
input:1
output:A00000001
input:99999
output:A00099999
**
here's the detailed demand:
Since it takes time and effort to enter the management number “alphabet + numeric value 9 digits” on the search screen, when the alphabetic number and the number excluding the leading 0 are entered, it is automatically complemented so that it becomes 9 padded with zeros.
sorry i'm very very new to programming in javascript
Try this:
May be what you want...
Please test it and tell if its what you want.
function getOutput(input){
var str=input.substring(1,input.length);
var padd0=9-str.length;
var zr="000000000";
var zrsub=zr.substring(0,padd0);
var output=input[0]+zrsub+""+str;
return output;
}
//Example: Call it like (NB any letter can be used):
getOutput("C123"); //or
getOutput("D123");
You can use .endsWith in js which takes a string and a search string and returns true if the specified string ends with the search string.
This function takes an array of customer ids and a search string and returns the matching customer id
function searchCustomer(customers, searchString) {
return customers.find(customer => customer.endsWith(searchString));
}
searchCustomer(['C000000123', 'C000000456'], 123); // "C000000123"
searchCustomer(['C000000123', 'C000000456'], 456); // "C000000456"
searchCustomer(['C000000123', 'C000000456', 'A00000001'], 1); //"A00000001"

jQuery Conditional Decimal Greater Than Comparison

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));

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));

regex for money values in JavaScript

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+)?)$

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

Categories

Resources