I am making a calculator in JavaScript and I want to know how to turn a string into an expression.
var numbers = "5+5+6";
numbers = +numbers;
document.querySelector('.screen').innerHTML = numbers;
Adding + before the variable does not seem to work. I would appreciate it if someone helped.
You can use the eval() function like this:
var numbers = "5+5+6";
document.querySelector('.screen').innerHTML = eval(numbers);;
Evaluate/Execute JavaScript code/expressions:
var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";
var res = a + b + c;
The result of res will be:
200
4
27
Without using eval, which is cheating - you could always write a simple calculator app.
First, take advantage of String.split() as follows
var numbers = "5+5+6";
numbers.split("");
// => ["5","+","5","+","6"]
Now all you need to do is figure out how to evaluate it while keeping the order of operations correct. Hint: it might involve trees.
Try using String.prototype.match() , Array.prototype.reduce() , Number() . See also Chrome App: Doing maths from a string
var numbers = "5+5+6";
var number = numbers.match(/\d+|\+\d+|\-\d+/g)
.reduce(function(a, b) {
return Number(a) + Number(b)
});
document.querySelector(".screen").innerHTML = number;
<div class="screen"></div>
Related
I have a number which looks number this:
800.60000305176541
This number changes all the time.
So I'm doing this:
var mynumber = 800.60000305176541
var changenumber = mynumber.toFixed(3);
This is displaying 800.600 ... I need it to display the last 3 like:
800.541
How can I do this?
You can convert to string and do your manipulations.
Please note we are loosing the right most digit due to limits of javascript.
var num = 800.60000305176541;
var str = "" + num
var arr = str.split(".");
var result = arr[0]
if (arr[1]) {
result += "." + arr[1].slice(-3)
}
console.log(num)
console.log(result)
You could also try to solve it mathematically.
800.60000305176541
800.60000305176000 -
------------------
800.00000000000541
.00000000000541
10^10. X
------------------
0,541 + 800 = 800.541
I really need your help with this since this goes well beyond my level of capability of javascript coding.
I'd like to design a function that would accomplish one of the following two scenarios:
If there is no dash and number at the end of the string var 'fileno', then rewrite the string fileno and add the dash and then the count at the end.
var fileno = 'test'
var c = 4
fileno = 'test-4'
If there is already a dash and then a number at the end of the string, replace the dash-number with the new info below:
var fileno = 'test-2'
var c = 3
fileno = 'test-3'
You may use regular expression with String.prototype.replace():
fileno = fileno.replace(/-\d+$|$/, '-' + c);
It literally means: replace -{number} or nothing at the end of the string with -{c}.
var c = 3;
console.log( 'test'.replace(/-\d+$|$/, '-' + c) );
console.log( 'test-4'.replace(/-\d+$|$/, '-' + c) );
if(fileno[fileno.length - 2] === "-"){
fileno = fileno.substr(0,-1) + c;
} else {
fileno += "-" + c;
}
Just either append a new number if there is already a - in the second last position or append a new one.
I have a program that reads a specific text file from a coding challenge that I've recieved and it takes the numbers and puts it into an array for me to solve a quadratic equation. When I go to display my answers I keep getting the NaN error on all of my values and I cant find where I messed up.
CODE
var lines = data[0].split("/n");
var numQuads = lines[0];
for (var i = 1; i < numQuads; i++){
var fields = lines[i].split(",");
var a = fields[0];
var b = fields[1];
var c = fields[2];
}
a = parseInt();
b = parseInt();
c = parseInt();
var discr = (b * b) - (4 * (a * c));
var sqrDiscr = Math.sqrt(discr);
var x = (-b + sqrDiscr) / (2*a);
var y = (-b - sqrDiscr) / (2*a);
var outputL = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has no real roots!";
var outputW = "The quadratic equation with coefficients A = " + a + " B = " + b + " C= " + c + " has roots x = " + x + " and x = " + y;
if (discr >= 0) {
output += outputW + "\n";
}
else {
output += outputL + "\n\n";
}
You did not provide an argument to the parseInt function. It works like this: parseInt("2") for example. You probably want to use parseFloat instead of parseInt.
Another remark: your data array is undefined.
you have insert String in parseInt()
a = parseInt("67");
b = parseInt("3");
c = parseInt("2");
Should probably be:
a = parseInt(a);
b = parseInt(b);
c = parseInt(c);
the problem was var lines = data[0].split("/n");
I used the wrong character. It was supposed to be var lines = data[0].split("\n");
The problem is that you are not parsing anything with your parse int.
Take a look here for some docs on parseInt.
Anyway that's how it should look like in your code:
a = parseInt(a, 10);
b = parseInt(b, 10);
c = parseInt(c, 10);
d = parseInt(d, 10);
EDIT: following the suggestion of #d3l I looked into the parseInt parameters, according to this question there could be some unexpected behaviours of the parseInt function without adding the radix parameter. Hence I added it to my solution.
Assuming you are parsing integers we can specify 10 as base.
I have 2 numbers
a = 1548764548675465486;
b = 4535154875433545787;
when I sum these number they are rounded to
a => 1548764548675465500
b => 4535154875433545700
and a + b returns 6083919424109011000 while it should return 6083919424109011273
is there a javascript solution to solve this problem witout the use of a library ?
To work around the precision limitations associated with JavaScript's numbers, you will need to use a BigInteger library like the popular one offered here: http://silentmatt.com/biginteger/
Usage:
var a = BigInteger("1548764548675465486");
var b = BigInteger("4535154875433545787");
var c = a.add(b);
alert(a.toString() + ' + ' + b.toString() + ' = ' + c.toString());
// Alerts "1548764548675465486 + 4535154875433545787 = 6083919424109011273"
Demo: http://jsfiddle.net/69AEg/1/
There are no integers in Javascript, all numbers are double precision floating point.
That gives you a precision of around 15-16 digits, which is what you are seeing.
as per this question
and potential solution i.e. use a library
Personally, I would not use javascript, never been great at numbers. Just try typing 0.1 + 0.2 into any browsers console window. Result is 0.30000000000000004.
Send the calculation to your server side language (as a string) and do the work there, you should have a better outcome.
Technical article on the nuances of floating point numbers here, if you interested
Well, here is a solution I found witout the use of any external library, all I need to do is to define a class that had a property value wich should be a string, and define the function plus
function LongNumber()
{
// it takes the argument and remove first zeros
this.value = arguments[0].toString();
while(this.value[0]==="0")
this.value = this.value.substr(1);
// this function adds the numbers as string to another string and returns result as LongNumber
this.plus = function (Num)
{
var num1 = pad(Num.value.length, this.value);
var num2 = pad(this.value.length, Num.value);
var numIndex = num1.length;
var rest = 0;
var resultString = "";
while (numIndex)
{
var number1 = parseInt(num1[(numIndex)-1]);
var number2 = parseInt(num2[(numIndex--)-1]);
var addition = (number1+number2+rest)%10;
rest = parseInt((number1+number2+rest)/10);
resultString = addition.toString() + resultString;
}
return new LongNumber((rest?rest.toString():"") + resultString);
}
function pad(width, string)
{
return (width <= string.length) ? string : pad(width, '0' + string)
}
}
All i need to do now is to declare 2 LongNombers and use the function plus
var Number1 = new LongNumber("1548764548675465486");
var Number2 = new LongNumber("4535154875433545787");
var Result = Number1.plus(Number2);
Result.value // returns "6083919424109011273"
How can i prevent to javascript interpret my numeric vars from string vars?
var a = 100;
var b = -10
var c = a + b // 10-10 (string)
lets say i allways want
var c = a + b = 100+(-10) = 90 (number)
In your example c will always be 90, however;
var a = 100;
var b = "-10";
var c = a + b // "100-10" (string)
to prevent this convert the string to an integer;
var c = a + parseInt(b, 10);
or with a unary+
var c = a + +b;
Your code example...
var a = 100;
var b = -10
var c = a + b // 90 (number)
...won't do that unless one of the operands is a String. In your example, both are Number.
If you do have numbers inside of Strings, you can use parseInt() (don't forget to pass the radix of 10 if working in decimal) or possibly just prefix the String with + to coerce it to Number.
Your code works fine. See here.
JavaScript will always do the latter, as long as both of the variables you are adding are numbers.
The most concise way is prepending a + if you aren't certain whether the variables are numbers or strings:
var a = "100";
var b = "-10";
var c = +a + +b; // 90
This works since +"123" === 123 etc.