Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm currently making a calculator with HTML, CSS and Javascript, for practice. I found out that the "built in" eval function did the math from a string. But it doesn't work properly.
I don't know what the problem is. But when i for example do: 11+11/2 which should be 11. Becomes 16.5 for some reason. I have no idea why. I would really appreciate some help.
Here is the code:
function revealAnswer(){
var math = document.getElementById("numbersInputted");
math.innerHTML += " = " + eval(math.innerHTML);
}
There are a whole bunch of reasons why this is the wrong approach.
First, innerHTML returns a string containing, not only the text content of an element, but also any nested HTML elements as well. If it's just the text you want, use textContent.
Next, by having the user input the actual math operator they want to use in the same string with the numbers creates more confusion. Have the user enter that separately and then you can use if/then logic to ultimately use the correct operator.
Next (and this is the important part), don't ever use eval(). It is not required to solve just about any problem you could encounter, but it opens up the door to "Cross Site Scripting" attacks on your website. Additionally, it manipulates the this binding and executes its code in its own scope.
What you really need to do is simply convert the string input into a number so that you can do math with it. You can do this with parseInt() and parseFloat()
So, your line could be:
math.innerHTML += " = " + parseFloat(math.textContent);
Lastly, for math, the order of operations is:
Parenthesis
Exponents
Multiplication
Division
Addtion
Subtraction
You can see that division is done prior to addition and that means that in your expression: 11 + 11/2, first 11/2 is evaluated (5.5) and then it is added to 11 (16.5).
Finally, remember that the + operator in JavaScript can mean mathematical addition or string concatenation and if one of the operands is a string, the other will be converted to a string.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last year.
Improve this question
let num = 231.32;
console.log( num.toPrecision() );
console.log( String(num) );
{
let numStr = "250";
console.log(Number(numStr)); console.log(Number.parseFloat(numStr));
}
Here we can achieve same things that String() and Number() can do by other ways. The above code gives same output. So shall we try to minimize the use case of String() and Number(). Which one would be nice ?
There is never really a real bad method just depends on the situation you are working on.
ToPrecision() will change the original number and round to specific decimal:
Note that ToPrecision() could only deal with number and will produce error with deal with string.
The toPrecision() method returns a string representing the Number object to the specified precision
Number v.s ParseFloat is almost the same in most of the situation, but Number will return NaN and parseFloat will return the number part when deal with a string that contain some characters and number. (e.g 123ABC)
Example:
let num = '123ABC'
//return 123
console.log(parseFloat(num))
//return NaN
console.log(Number(num))
let num1='123'
//Produce error
console.log(num1.toPrecision(2))
I think the main difference between String and use " " is that you can't always and it is very annoying to redeclare the things you want (e.g. redeclare ABC to "ABC"). (I think your numStr is to show use " " change string.
Another built-in function to use is toString() to convert to string, but toString will produce error when you use want to convert null and undefined.
Example:
let test = undefined;
//produce 'undefined'
console.log(String(test))
//produce error
console.log(test.toString())
I think it is OK to use any of them in the most situation, but you have to notice the small difference. They are not totally same.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
let num = 100;
document.write("Num: " + num + "");
document.write("Binary: " + num.toString(2) + "");
document.write("8: " + num.toString(8) + "");
document.write("16: " + num.toString(16));
//I want this, but without toString() or any other method.
welcome to Stack Overflow! This sounds like a homework question, because you have been asked to implement something that would normally be done using builtin methods. Here is the outline of how I would approach this, to help you get started.
If you had to write the number 100 in base 16, what would the last digit of the answer be?
How did you come to that conclusion?
Now what would the decimal value of the remainder of the hexadecimal number have to be? Hint: answer = 96.
How did you come to that conclusion?
Your last answer will be a multiple of 16, because you have removed already the remainder after dividing by 16. You have done: number - (number modulo 16).
If you divide this by 16, you have a new, smaller number, which again you can convert into hexadecimal in the same way as above. In this manner you can keep extracting one hexadecimal digit at a time, until there is no reminder.
This gives your hexadecimal number, outputted in reverse order.
You can do the same for any base.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
i am trying to round a numeric value to upto 2 decimal places in javacript.
Please try to access the following url
https://www.jsnippet.net/snippet/1665/1/Rounding-a-value-upto-2-decimal-places
If you notice the code i am trying to round the following values
3.225 , 4.225 and 5.225
If you notice the result, 3.225 is rounded of to 3.23 which is correct.
Also 5.225 is rounded of to 5.23 which is also correct but 4.225 is getting rounded of to 4.22 instead of 4.23
Can anyone please tell me how to fix this.
try this..
Number(Math.round(3.225+'e2')+'e-2');
This is a painful task on Javascript. From my experience, I do things like this:
function round(n, places = 2) {
var epsilon = Number.EPSILON*1000;
var exponent = Math.pow(10, places);
var integral = Math.round((n+epsilon) * exponent);
return integral/exponent;
}
epsilon is a very small number to compensate this behavior of floats in JavaScript.
Note: please don't use this function for sensitive data, is just a very very simple rounding function.
if you have to deal with sensitive data, use MathJS as user King suggested.
Use the mathjs library, provided here. The round function provided by this library is more precise than the builtin library. I've already tested your code using it and it works!
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an object with all available country codes. and I want to know how I can get the country code by a given phone number and display the corresponding country name. the phone number will look like 16041234567(Canada/US +1) or maybe 8601012345678(China +86) or any other country phone number without plus(+) in the front. I just want to get the country code then I know how to display the name. looks like the code can be 1 up to 4 digits.
FIRST ANSWER:
Just a quick thought, why not count from the other side.
take the 10 numbers off the back side of the number. What you are left with will be the truncated country code.
from your example:
num = "16041234567";
code = num.slice(0, num.length-10);
country_name = country_code_object[code];
This code assumes that your object can deal with variable length codes (but you could always buffer the front of the code if you needed to.
BROKEN: China does not use 10 number (cells use 11)
FIX:
After looking into country codes more completely I relised they are a prefix tree. This means that for a liner time you can just check character by character
num = "16041234567";
country_code;
i = 1;
while (!country_code || i < num.length) {
country_code = country_code_obj[num.slice(0, i)];
i++;
}
The nature of country codes will guarantee that the first code that works will be the correct one. (and we can imagine that this must be true, the phone company doesn't know when you are done typing numbers. They just know when you've reached the end of a valid country code)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I'd like to make a transliterator from the Korean alphabet (hangul) to the Latin alphabet (romanization) but it seems that (after having been trying many times without success) the use of a simple associated array isn't the proper thing to do.
Here is the method I have been trying to work hard on so far:
https://gist.github.com/1154969
I tried replacing the Hiragana by Korean syllables but I couldn't get it working.
Does anyone have a solution?
Romanizing a text is easy, but the other way around is quite difficult. For instance in Japanese (which I know better than Korean), なん is written as "nan", the first syllable being "na" and the second being "n". Your code would have to distinguish between the two syllables in some way, because if it would turn the first n into a ん instead of the second, your parser would be left with "an", which is a non-existent syllable in Japanese.
The way to approach this would in its most basic form involve an associative array. Instead of mass-replacing the keys with their values in one go, you'd have to look for the longest possible syllables first and replace those in one go. So first, you'd go for syllables like "shi", the for syllables like "na" and lastly for syllables like "n". If you do it that way, all Asian languages I know of should be safely converted back into their own alphabet, though keep in mind that this may still cause problems if different syllables have the same Romanized form of writing.
Since you simply want to expand some specific symbols (hangul syllables) in original string to other pre-defined sequences (romanization), use combination of object lookup where you'd store hangul as key and romanization as value and String.replace's ability to generate replacements through function.
I'll use katakana as part of example because I too know Japanese better :) but you only need to fill replacement table with correct hangul for it to work:
var hangul_syllable_to_roman = {
'가' : 'ga',
'강' : 'gang',
'カ' : 'ka',
'タ' : 'ta',
'ナ' : 'na'
}
function one_hangul_syllable_to_roman(syllable) {
var roman = hangul_syllable_to_roman[syllable]
// if we have suitable replacement - do it, if not - just return original back
if (roman) { return roman } else { return syllable }
}
function hangul_to_roman(hangul) {
return hangul.replace(/./gm, one_hangul_syllable_to_roman)
}
document.write(hangul_to_roman('가강 カタカナ some other text'))
// gagang katakana some other text