Function works in console but not jQuery - javascript

I'm creating a simple binary to decimal converter page with an option to compare. My binary to decimal function works fine and jQuery can run and display it to the DOM. My compare function works fine in console but doesn't work when called on by a jQuery click function. Console.log works with the exact same numbers outside of the jQuery function, but not inside. Here's the jsfiddle: https://jsfiddle.net/deniswells59/ekdtk60t/
//simple compare function
var result = "";
var assert_equal = function(bin, dec) {
if(bin === dec){
return result = ("They are Equal!");
} else {
return result = ("They aren't Equal!");
};
};
//this works fine as well as .binaryToDecimal(), which I didn't include
$("#convert").click(function(){
var value = $("#binToConvert").val();
var valueConverted = value.binaryToDecimal();
$("#display").html("<span class='results'>"+value+"</span> converts to <span class='results'>"+valueConverted+"</span>");
});
//this ALWAYS displays "They aren't Equal!"; console.log says otherwise
$("#compare").click(function() {
var binary =$("#binary").val();
var decimal =$("#decimal").val();
binary = binary.binaryToDecimal();
assert_equal(binary, decimal);
$("#display").html("<span class='results'>"+result+"</span>");
});

You need to make sure they're the same type. Right now bin is a number and dec is a string (because jQuery's .val() always returns a string, even if the user entered a number). bin is a number because your binaryToDecimal function returns a number.
Just convert dec and bin to the same type before you compare them in your assert_equal function. Otherwise you can just use == if you do not care about type.
Something like this should do the trick:
var assert_equal = function(bin, dec) {
if(parseInt(bin) === parseInt(dec)){
return result = ("They are Equal!");
} else {
return result = ("They aren't Equal!");
};
};

You should add the function to the assert_equal as below
var assert_equal = function(bin, dec) {
if(bin.binaryToDecimal() == dec)
return result = ("They are Equal!");
}

Related

Can I check on what an integer ends in Javascript

I want to remove the decimals after a price if it ends on ',00'. If it ends on anything else it should remain. I'll have to be able to see on what the price ends to do so, but how do I achieve this in Javascript?
My idea was checking if the price ended on 00 and removing it in an if statement.
function gformFormatMoney(text, isNumeric){
if(!gf_global.gf_currency_config)
return text;
var currency = new Currency(gf_global.gf_currency_config);
var unformatted = currency.toMoney(text, isNumeric);
var formatted;
var formatting = unformatted%10;
if(formatting == 00) {
}
return unformatted;
}
^This gives a error 'Octal litterals with the prefix 0 are not allowed'
You need to parse your numbers as a float, fix it to 2 decimals (in all cases), and remove any matches for (.00). Something like this could work:
function fixFloat(num){
return parseFloat(num).toFixed(2).replace('.00', '');
}
console.log(fixFloat(20.00));
console.log(fixFloat(40.40));
console.log(fixFloat(30.01));
Please be aware that this will return a string. If you wish to convert this back to a number, you'll need to parse it again.
You should use toFixed.
as for :
let num = 50.00;
num.toFixed(2).includes('.00') ? num.toFixed() :num.toFixed(2);
If the data type is not string , the trailing zeros after decimal will be removed. If it is a string use parseInt to convert to number
let price = 20.00;
console.log(price)
let price1 = '40.00'
console.log(parseInt(price1, 10))
let price2 = '40.00'
console.log(parseFloat(price2, 10))
Turns out it wasn't an integer, but a string.
I fixed it by doing:
function gformFormatMoney(text, isNumeric){
if(!gf_global.gf_currency_config)
return text;
var currency = new Currency(gf_global.gf_currency_config);
var unformatted = currency.toMoney(text, isNumeric);
var formatted = unformatted.replace(',00', '');
return formatted;
}

Attempting to create a very simple JavaScript function that adds 7 to the user's inputted number

I'm trying to create a function that will take the user's inputted number and simple add 7 to it in JavaScript. I'm doing this in the console on my Firefox browser. I get the prompt as expected but after that it just displays undefined, I can't understand why. I tried to change the parameter to just the number variable but that didn't work out. Here's my code:
var number =prompt("Pick a number");
function add7(NewNumber){
NewNumber = 7 + number;
return (NewNumber);
}
Try this:
function add7(){
return parseInt(prompt("Pick a number"))+7;
}
add7();
prompt() returns a string so you first have to parse that value.
I have also removed unnecessary assignments from your code.
You should call your function like below.
function add7(number) {
number = number + 7;
console.log(number);
}
add7(3);
You should prompt inside the function, not outside
Also you don't need to pass any parameters to that function:
function add7(){
var number =prompt("Pick a number");
var NewNumber = 7 + parseInt(number);
return (NewNumber);
}
add7();
Convert the string to an integer.
var number =prompt("Pick a number");
function add7(NewNumber){
NewNumber = 7 + parseInt(number);
return (NewNumber);
}
If you paste this example directly into your browser console window, it should give you the desired effect.
var number = prompt("pick a number")
function add7(NewNumber){
NewNumber = 7 + parseInt(number);
return (NewNumber);
}
console.log(add7(number))

remove decimal in javascript

I want to remove decimal from number in javascript:
Something like this:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
I can not use Math.round(number). Because, it'll give me different result. How can I achieve this? Thanks.
The simplest way to handle the first three examples is:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
This assumes that the argument is a number already, in which case your second and fourth examples are impossible.
If that's not the case, you'll need to count the number of dots in the string, using something like (trick taken from this question):
(str.match(/\./g) || []).length
Combining the two and throwing, you can:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
This will work for most numbers, but may run into rounding errors for particularly large or precise values (for example, removeDecimal("1398080348.12341234") will return 139808034812341230).
If you know the input will always be a number and you want to get really tricky, you can also do something like:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
You can use the replace method to remove the first period in the string, then you can check if there is another period left:
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
// invalid input
}
Demo:
function reformat(str) {
str = str.replace('.', '');
if (str.indexOf('.') != -1) {
return "invalid input";
}
return str;
}
// show in Stackoverflow snippet
function show(str) {
document.write(str + '<br>');
}
show(reformat("12"));
show(reformat("12.00"));
show(reformat("12.12"));
show(reformat("12.12.12"));
How about number = number.replace(".", ""); ?

Validating a data input javascript

I have been looking to validate the data input to check whether it is a integer or a string. I looked around and saw some suggestions and typeof suggestions but nothing seems to work.
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
var mk1 = parseInt(mk1);
mark1.push(mk1);
If you want to check whether input string is not a number try this:
if (isNaN(parseInt(name, 10)) {
//name is String
} else {
//name is Number
}
use the === operator as below
if (mk1 === parseInt(mk1 , 10))
alert("mk1 is integer")
else
alert("mk1 is not an integer. May be String")
If you don't know that the argument is a number-
function isInt(n){
return Number(n)===n && n%1===0;
}
Try this way to find input type;
if(!isNaN(parseInt(mk1)))
// for integer
else if(!isNaN(parseFloat(mk1)))
//for float
else
// String
When you prompt() the user for data, you always get a string. If you want to check, whether it actually contains just a number, you can try this:
var value = prompt('...'),
num = parseInt(value, 10);
if (num == value) {
// ... it is an integer, use `num`
} else {
// ... it's not an integer (or not *just* an integer), use `value`
}
(or use parseFloat(value) for real numbers).
It's hard to say what are you trying to do really. You seem to declare var mk1 twice, which looks a bit strange. Also, even if parseInt fails (then returns NaN [Not a Number]) you add it to mark1, which is probably not what you want. Have a look at this:
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
mk1 = parseInt(mk1);
if (Number.isNaN(mk1) === false) {
mark1.push(mk1);
} else {
alert("mark 1 is not a number");
}
Use this function:
isNaN(parseInt(mk1))
It will return "true" if not a number, and "false" if a number

Round the value in Javascript

I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();

Categories