Unexpected output in javascript - javascript

I am beginner to javascript and i am getting unexpected output
here is the code
<script type="text/javascript">
function add(a,b)
{
x = a+b;
return x;
}
var num1 = prompt("what is your no.");
var num2 = prompt("what is another no.")
alert(add(num1,num2));
</script>
it should give output as a sum of two number entered by us on prompting but it is simply concatenating the two number and popping the output

This is because the prompt function returns a String and not a Number. So what you're actually doing is to request 2 strings and then concatenate them. If you want to add the two numbers together you'll have to convert the strings to numbers:
var num1 = parseFloat(prompt("what is your no."));
var num2 = parseFloat(prompt("what is another no."));
or simpler:
var num1 = +prompt("what is your no.");
var num2 = +prompt("what is another no.");

prompt returns a string, not a number. + is used as both an addition and concatenation operator. Use parseInt to turn strings into numbers using a specified radix (number base), or parseFloat if they're meant to have a fractional part (parseFloat works only in decimal). E.g.:
var num1 = parseInt(prompt("what is your no."), 10);
// radix -----^
or
var num1 = parseFloat(prompt("what is your no."));

When you prompt the user, the return value is a string, normal text.
You should convert the strings in numbers:
alert(add(parseInt(num1), parseInt(num2));

The return value of prompt is a string. So your add function performs the + operator on 2 strings, thus concatenating them. Convert your inputs to int first to have the correct result.
function add(a,b)
{
x = parseInt( a ) + parseInt( b );
return x;
}

In addition to the already provided answers: If you're using parseInt() / parseFloat(), make sure to check if the input in fact was a valid integer or float:
function promptForFloat(caption) {
while (true) {
var f = parseFloat(prompt(caption));
if (isNaN(f)) {
alert('Please insert a valid number!');
} else {
return f;
}
}
}
var num1 = promptForFloat('what is your no.');
// ...

Related

How to convert string representing a decimal using parseInt instead of parseFloat?

Given a string that represents a number use parseInt to convert string to number. I wrote a working function, but did not account for decimal numbers. Is there a way to convert decimals using parseInt? This is as far as I've gotten trying to account for decimals. The problem with this is NaN being returned. I can't think of a solution to implement that filters NaN from the results. The ultimate goal is to compare the two strings. My solution must use parseInt.
function convertStr(str1, str2) {
let num1 = str1.split('')
let num2 = str2.split('');
num1 = num1.map(str => parseInt(str));
num2 = num2.map(str => parseInt(str));
console.log(num1);
console.log(num2);
}
Any help is greatly appreciated.
I think this is a good step to what you are seeking for :
The question is : What do you want as output when encountering decimal value?
// Soluce to replace NaN by '.'
function convertStrReplace(str1) {
let num1 = str1.split('')
num1 = num1.map(str => parseInt(str)).map(x => isNaN(x) ? '.' : x);
console.log(num1);
}
// Soluce to ignore NaN
function convertStrIgnore(str1) {
let num1 = str1.split('')
num1 = num1.map(str => parseInt(str)).filter(x => !isNaN(x));
console.log(num1);
}
convertStrReplace('17,52');
convertStrIgnore('17,52');
Syntax alternative
function convertStrFilter(str1) {
const num1 = [
...str1,
].map(str => parseInt(str)).filter(x => !isNaN(x));
console.log(num1);
}
convertStrFilter('17,52');
Explaination about integer and string differences
// String and integer differences
// Put a number into a string
const str = '9000';
console.log(typeof str, str);
// Put a number into a number
const number = 9000;
console.log(typeof number, number);
// Compare both (compare value and type)
console.log('equality ===', str === number);
// Compare both (compare value)
console.log('equality ==', str == number);
const numberFromString = parseInt(str);
console.log(typeof numberFromString, numberFromString);
// Compare both (compare value and type)
console.log('equality ===', number === numberFromString);

js function ignores Decimal Numbers

So i made a function that calculate the price by multiplication how many meters i put the problem is when ever i put decimal numbers it ignores it
heres my script
<script>
function getFillingPrice() {
cake_prices = document.getElementById('price').value;
filling_prices = document.getElementById('test2').value;
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
return t*x;
}
function calculateTotal() {
var total = getFillingPrice();
var totalEl = document.getElementById('totalPrice');
document.getElementById('test3').value =total + " دينار ";
totalEl.style.display = 'block';
}
</script>
You're converting the values to integers when you get them from the DOM.
Change this...
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
to this...
var t=parseFloat(filling_prices);
var x=parseFloat(cake_prices);
Beside the parsing problem, you could use
an unary plus + and
a default value for non parsable value, like letters or an empty string (falsy values) with a logical OR ||.
cake_price = +document.getElementById('price').value || 0
// ^ unary plus for converting to numbner
// ^^^ default value for falsy values
Together
function getFillingPrice() {
var cake_price = +document.getElementById('price').value || 0,
filling_price = +document.getElementById('test2').value || 0;
return cake_price * filling_price;
}

Comparing the numeric values of each array properties in Javascript

I am trying to find a solution for this:
Users are asked to type in a random set of numbers sequentially:
var num1 = prompt("Enter 1st set of numbers");
var num2 = prompt("Enter 2nd set of numbers");
var num3 = prompt("Enter 3rd set of numbers");
var myNumbers =[num1, num2, num3];
Now I am trying to take compare the sum of the digits in each element of the array. For instance, if myNumbers[0] = 32, myNumber[1] = 45, what's the function to compare 5 (3+2) and 9 (4+5)?
I am trying to compare the sum of each elements by adding the numbers in that element, and return the largest number. So if num1= 1234, then the sum of myNumbers[0] should be 10. By comparing , if num2 = 3456, then the sum should be 18, the function should return num2.
var num1 = prompt("Enter 1st set of numbers");
var num2 = prompt("Enter 2nd set of numbers");
var num3 = prompt("Enter 3rd set of numbers");
// finds the sum of your array, parsing each element as an integer
var sum = function(array){
var digits = array.split("")
return digits.reduce(function(a, b) {return parseInt(a, 10) + parseInt(b, 10)})
}
var myNumbers =[num1, num2, num3]
var findLargest = function(array){
var answer
var largest = 0
array.forEach(function(input){
// check if this is the largest sum
if (sum(input) == largest){
// check if there is already a running set of equal sums
if (typeof(answer) == Object) answer.push(input)
// create set of equal sums if not
else answer = [answer, input]
}
else if (sum(input) > largest) {
largest = sum(input)
answer = input
}
})
return answer
}
alert(findLargest(myNumbers))
https://jsfiddle.net/gmebk2Ly/7/
This also checks to see if there are multiple inputs that are equal
If you want to sort the list by the sums of the digits, you can do the following. The comparator function finds the sum of the digits in the members of the list, then compares them. If you just wanted to sum the digits in the string, you can just extract the code that does this from this solution too.
myNumbers.sort(function(a,b) {
var sumA = 0;
var sumB = 0;
a.split("").forEach(function(digit) {
sumA+=parseInt(digit);
});
b.split("").forEach(function(digit) {
sumB+=parseInt(digit);
});
return sumA-sumB;
});
Let's break this down into two sub-problems: first, finding the sum of digits; second, finding the maximum value of an array. For the second, we already have Math.max.
For the first, we'll break it down even further and first write a function just to get the digits:
function digits(x) { return String(x).match(/\d/g).map(Number); }
To sum up the digits, we just say
function sumDigits(x) { return sum(digits(x)); }
For sum, you can find many examples here on SO, but the simplest one is
function sum(array) { return array.reduce(add, 0); }
add is easy enough:
function add(a, b) { return a + b; }
Now, to get the maximum sum of digits from each element of an array:
function maxSumDigits(array) { return Math.max(...array.map(sumDigits)); }
The above uses ES6 spread operator. In ES5:
return Math.max.apply(0, array.map(sumDigits));
The advantage of writing your code this way is first, you end up with useful little utility routines that you can re-use; second, the code is easier to read and prove to yourself that it's right; and third, it's easier to deal with spec changes, such as wanting to find the minimum instead of the maximum, of the product of digits instead of the sum.
function digits(x) { return String(x).match(/\d/g) . map(Number); }
function sumDigits(x) { return sum(digits(x)); }
function sum(array) { return array . reduce(add, 0); }
function add(a, b) { return a + b; }
function maxSumDigits(array) { return Math.max(...array . map(sumDigits)); }
console.log(maxSumDigits([1234, 3456]));
This returns the largest sum. To find the element whose digits have the largest sum, the easiest way would be to remember the array of sums of digits, then look that up:
function maxSumDigits(array) {
var sums = array . map(sumDigits);
var max = Math.max(...sums);
return array[sums.indexOf(max)];
}

how to round up if value is two decimal and format as 3 decimals in javascript?

Test cases:
var num1 = 10.66;
var num2 = 10.7898
The function I found on stackOverFlow:
function formatUserCurrencyValue(fieldValue){
var num = parseFloat(fieldValue);
var str = num.toFixed(10);
str = str.substring(0, str.length-7);
return str;
};
I would like the result to be like this: if 10.66 then 10.670 and if 10.78998 then 10.789. Basically if the value has 2 decimal places then the result should round up the first and then format as 3 decimals. If more than 2 decimals (eg. 10.78998) then 10.789, trimming out values after 3 decimals.
Could somebody please tell me how I can achieve this? I tried with the above function as well as some others I found but the result is not what I expected for the 10.66 scenario. I am getting 10.660 instead of 10.670.
It looks like a similar question has already been asked here: Formatting a number with exactly two decimals in JavaScript
I liked the answer that #Miguel had. Using a function to do the conversion.
function precise_round(num, decimals) {
var t=Math.pow(10, decimals);
return (Math.round((num * t) + (decimals>0?1:0)*(Math.sign(num) * (10 / Math.pow(100, decimals)))) / t).toFixed(decimals);
}
Then use the function.
precise_round(num,3)
Setting aside the fact that rounding num1 will produce 10.66 and not 10.67 what you want can be achieved with the below function which will print the appropriate results to the console.
var num1 = 10.66;
var num2 = 10.7898;
var roundIt = function(num) {
console.log(parseFloat(Math.round(num * 1000) / 1000).toFixed(3));
};
roundIt(num2); //10.790
roundIt(num1); //10.660
Since using the toFixed() method returns a string we wrap the result in parseFloat() so that we get a floating point number.
Here you have what you ask, it seems weird to me. Round all like this is something "special" at least... but, is exactly what you ask.
var weirdRound = function(n) {
var splited = n.toString().split(".");
var res = 0;
if(splited[1]) {
var len = splited[1].length;
if(len > 3) {
splited[1] = splited[1].substr(0, 3);
res = (splited.join(".") *1).toFixed(3);
} else if(len == 2) {
splited[1] = splited[1].substr(0, 1) + ((splited[1].substr(len -1, len) *1) +1);
res = (splited.join(".") *1).toFixed(3);
} else if(len == 1) {
res = n.toFixed(2)
} else {
res = n.toFixed(3);
}
}
return res.toFixed(3);
}
console.log(weirdRound(10.66));
console.log(weirdRound(10.9));
console.log(weirdRound(10.7898));
console.log(weirdRound(1.12));
console.log(weirdRound(1.12565));
console.log(weirdRound(1.125));

math.round vs parseInt

Have a quick JS question. What is the difference between math.round and parseInt?
I made a JS script to sum the inverses of prompted numbers:
<script type="text/javascript">
var numRep = prompt("How many repetitions would you like to run?");
var sum = 0;
var count = 0;
var i = 1; //variable i becomes 1
while (i <= numRep) {// repeat 5 times
var number = prompt("Please enter a non zero integer");
if(number==0){
document.write("Invalid Input <br>");
count++;
}
else{
document.write("The inverse is: " + 1/number + "<br>");
sum = sum + (1/parseInt(number)); //add number to the sum
}
i++; //increase i by 1
}
if (sum==0){
document.write("You did not enter valid input");}
else { document.write("The sum of the inverses is: " + sum); //display sum
}
</script></body></html>
and it uses parseInt. If I wanted to makeit use math.round, is there anything else I need to do so that It knows to limit the number of decimal places accordingly?
In other words, does math.round have to be formatted in a certain way?
The two functions are really quite different.
parseInt() extracts a number from a string, e.g.
parseInt('1.5')
// => 1
Math.round() rounds the number to the nearest whole number:
Math.round('1.5')
// => 2
parseInt() can get its number by removing extra text, e.g.:
parseInt('12foo')
// => 12
However, Math.round will not:
Math.round('12foo')
// => NaN
You should probably use parseFloat and Math.round since you're getting input from the user:
var number = parseFloat(prompt('Enter number:'));
var rounded = Math.round(number);
Math.round will round the number to the nearest integer. parseInt will assure you that the value is a number
So what you will need is something like this:
number = parseInt(number);
if ( isNan(number) || number == 0 ){
document.write("Invalid Input <br>");
count++;
}
This will assure you that the use has put in a number
Math.round expects a number, parseInt expects a string.
Use parseInt('12345', 10) for parsing 10-based numbers.
http://www.javascripter.net/faq/convert2.htm

Categories