Output come as string [duplicate] - javascript

This question already has answers here:
Sum of two numbers with prompt
(10 answers)
Closed 2 years ago.
I just want to add two numbers but is result come as string . I use vscode.How can take input as integer ?
var num1 =prompt("enter a number");
var num2=prompt("enter a number");
var sum =num1+num2;
console.log(the of ${num1} and ${num2} ${sum} );

You need to change them to type Number before you can add them. User input from prompt() will always return a string. Try:
var sum = Number(num1) + Number(num2);

You use parseInt() or parseFloat() function, which is used for converting string to Int or Float type.
var sum = parseInt(num1) + parseInt(num2);

Use the parseInt(), or the parseFloat() function. These convert String to Int/Float type.
var sum = parseInt(num1) + parseInt(num2);

Related

Negative Numbers Give Error NaN in Javascript [duplicate]

This question already has answers here:
Math.pow with negative numbers and non-integer powers
(2 answers)
Closed 3 years ago.
I am trying to write a code about changing numbers to its cube root but whenever i enter a negative number, i receive NaN error.
Tried to use string to number function called Number
let number = prompt("Enter a number");
if (number > 0 || number < 0){
let x = number**(1/3);
alert(x);
}
else if (number == 0){
alert(number);
}
else{
alert("Error");
}
I enter -8 for example, i expect it will give me -2 as result but i receive NaN
This is because cube-root of a negative number has complex numbers as solutions along with a negative real number, to get the negative real number you have to write a simple logic:
function cubeRoot(number){
const isNegative = number < 0;
const cubeRoot = Math.pow(Math.abs(number), 1/3);
return isNegative ? -cubeRoot : cubeRoot;
}
console.log(cubeRoot(-8));
console.log(cubeRoot(0));
console.log(cubeRoot(8));
There is a library available to do this: math.js
console.log(math.cbrt(-8));
console.log(math.cbrt(0));
console.log(math.cbrt(8));
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/6.2.1/math.js"></script>

Convert to Number from a String but only strings that are valid integers [duplicate]

This question already has answers here:
How to convert a string to an integer in JavaScript
(32 answers)
Closed 4 years ago.
I have an input which is always a String. The string can contain an integer or text:
intputString = "1";
or
inputString = "hey";
I would like to convert to a Number only those inputs that contain integers. Otherwise, the inputs need to remain the same.
For example, if I have an integer:
inputString = "288"; // <-- Make the conversion
desiredOutput = 288;
And if I have non-integer text:
inputString = "hey"; // <-- Don't make the conversion and leave it as is
desiredOutput = "hey";
I was using Numbers(inputString) but this converts text values into NaN.
How can I achieve this conversion?
EDIT: None of the answers from the duplicate question answers this question.
Simply cast the input to Number. If the result is NaN, return the original string, else return the casted value.
function convert(input) {
if(input === "0") {
return 0;
}
return Number(input) || input;
}
console.log(convert("288"));
console.log(convert("hey"));
console.log(convert("0"));
console.log(convert(""));
Maybe something like this:
if(!isNaN(inputString))
output = inputString;
else
//Input is not a number

Addition operator not working in JavaScript

Addition operator isn't working for me in Javascript. If I do 5+5, it gives me 55 instead of 10. How can I fix this?
var numberOne = prompt (Enter first number.);
if (numberOne > 0.00001) {
var numberTwo = prompt(Enter the second number.);
if (numberTwo > 0.00001) {
var alertAnswer = alert (numberOne + numberTwo);
}
}
You're reading in strings, and concatenating them. You need to convert them to integers with parseInt.
IE:
var numberOne = parseInt(prompt("Enter first number."), 10);
There are two main changes that need to take place. First, the prompts must use Strings. Second, you must parse the user's String input to a number.
var numberOne = prompt ("Enter first number.");
if (numberOne > 0.00001) {
var numberTwo = prompt("Enter the second number.");
if (numberTwo > 0.00001) {
var alertAnswer = alert (parseInt(numberOne,10) + parseInt(numberTwo,10));
}
you need to use parseInt
as in
var a = parseInt(prompt("Please enter a number"));
Just for completeness: a potential problem with parseInt() (in some situations) is that it accepts garbage at the end of a numeric string. That is, if I enter "123abc", parseInt() will happily return 123 as the result. Also, of course, it just handles integers — if you need floating-point numbers (numbers with fractional parts), you'll want parseFloat().
An alternative is to apply the unary + operator to a string:
var numeric = + someString;
That will interpret the string as a floating-point number, and it will pay attention to trailing garbage and generate a NaN result if it's there. Another similar approach is to use the bitwise "or" operator | with 0:
var numeric = someString | 0;
That gives you an integer (32 bits). Finally, there's the Number constructor:
var numeric = Number( someString );
Also allows fractions, and dislikes garbage.

Jquery: + isn't working right

I am making a calculator for fun, but for some reason everything works but the addition.
Instead of adding two numbers, it is writing them both. For example 5 + 7 shows as being 57.
As I said before, -, /, and * are working fine. How should I fix this?
Here is the code:
$('.solve2').click(function(){
var num1 = $('#num').val();
var num2 = $('#number').val();
var ans = num1+num2;
alert(''+ans+'');
});
$('.solve2').click(function(){
var num1 = parseInt($('#num').val());
var num2 = parseInt($('#number').val());
var ans = num1+num2;
alert(''+ans+'');
});
Instead of parseInt, you can use parseFloat as stated in another answer.
EDIT:
As stated in the comments below, it's better to force the string to be interpreted as a decimal number. You can do this by adding the radix parameter.
var radix = 10; //decimal
var num1 = parseInt($('#num').val(), radix);
var num2 = parseInt($('#number').val(), radix);
Use parseFloat, it Parses a string argument and returns a floating point number.
var ans = parseFloat(num1)+parseFloat(num2);
As per your example it was working as cocantenation operator
Convert your values from strings to numbers. The + is both the addition operator and cocantenation operator.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators
Simple, you must cast your string to integer. Use parseInt
var num1 = parseInt($('#num').val());
var num2 = parseInt($('#number').val());
view my sample:
JSFiddle sample
When you get the value of an input element - either via plain JS or using jQuery's .val() - it returns as a string. And when one of the operands of + is a string and the other is a primitive - i.e. a number, string, boolean, undefined or null - then the other one is converted to a string and they are concatenated:
4 + " four" === "4 four"; // true
false + " is now a string" === "false is now a string"; // true
etc.
Therefore, your values returned from .val() are being concatenated, and you need to convert the strings returned from .val() into numbers using parseFloat:
$('.solve2').click(function(){
var num1 = parseFloat($('#num').val()),
num2 = parseFloat($('#number').val()),
ans = num1 + num2;
console.log(ans);
});

How can I change an HTML input value's data type to integer?

I'm using jQuery to retrieve a value submitted by an input button. The value is supposed to be an integer. I want to increment it by one and display it.
// Getting immediate Voting Count down button id
var countUp = $(this).closest('li').find('div > input.green').attr('id');
var count = $("#"+countUp).val() + 1;
alert (count);
The above code gives me a concatenated string. Say for instance the value is 3. I want to get 4 as the output, but the code produces 31.
How can I change an HTML input value's data type to integer?
To convert strValue into an integer, either use:
parseInt(strValue, 10);
or the unary + operator.
+strValue
Note the radix parameter to parseInt because a leading 0 would cause parseInt to assume that the input was in octal, and an input of 010 would give the value of 8 instead of 10
parseInt( $("#"+countUp).val() , 10 )
Use parseInt as in: var count = parseInt($("#"+countUp).val(), 10) + 1; or the + operator as in var count = +$("#"+countUp).val() + 1;
There is a parseInt method for that or Number constructor.
var count = parseInt(countUp, 10) + 1;
See w3schools webpage for parseInt.

Categories

Resources