Purpose of dividing by 1 javascript - javascript

I was working on a simple programming exercise my teacher gave us, and I noticed several times that in Javascript, I have to divide a number by 1, otherwise it will return a ridiculous value. Any explanations?
I have a jsfiddle
http://jsfiddle.net/TpNay/1/
var widthrand=Math.floor(Math.random()*widthRange);
width=widthrand + document.getElementById('width').value/1;
If you look at line 22, and take out the divide by 1, and click generate, it will return ridiculous lengths
Thanks

It makes JavaScript type juggle forcing the value of document.getElementById('width').value to become numeric.
A better way to do it would be parseInt(document.getElementById('width').value, 10)

Related

Adding a whole number and a decimal in Javascript results in removal of the decimal?

I'm sure this is simple, but in my javascript code, I have two numbers. One contains a decimal, and the other doesn't, and I add them together (ie. 7.5 + 5), I am getting a result with NO decimal value.
Do I need to cast each number variable as a double? I know that all numbers are doubles in javascript - which is why I do not understand this behavior...
For instance, I have var answer = week1 + week2;. Does this make sense?
Thanks in advance!
I am sorry for wasting time - turns out I was using parseInt instead of parseFloat to gather the "week" values I spoke about.
Can someone please close this question or delete it? Before the shame consumes me?

Generate random numbers based off of a seed value

Someone brought up the idea of generating random numbers in the exact same order based off of a seed value, and I started thinking extremely hard on how to do this. We challenged eachother to create an application that does the following:
Generate a set of five random numbers ranging from 1 to 100 every ten seconds based on a seed value. The numbers generated (while using the same seed value) should be exactly the same and generated in exactly the same order, therefor if the application is ran for 20 seconds and the numbers [1, 17, 2, 58, 27, 83, 32, 56, 27, 4] are generated, if the application is restarted these exact same numbers should be generated after 20 seconds, if the same seed was provided.
This will allow for multiple clients to generate the same exact information based off of a single numeric seed value.
Unfortunately after a few days we've both ended up falling short and we're completely clueless as to how to do this. We don't even really know what the proper term for this type of behavior is, however I've called it "Deterministic number generation"
I've tagged both languages that we tried using for this expirement, hoping someone can help us out. This would be a very interesting block of code to experiment with, and we've even thought of ways to improve some of our mobile games by using this strategy, if we can find a way to do it.
Any help would be graciously appreciated.
At risk of stating the obvious, but in C# this would be -
int seed = 12;
Random r = new Random(seed);
for (int n = 0; n < 20; n++)
{
Console.WriteLine("{0}", r.Next(1, 100));
}
Where as long as you both use the same seed number you should get the same list ...
Unless I a missing something in your question here ...

Make large numbers worth less than small numbers (JS)

I need to find out how to make smaller numbers worth more than bigger numbers, and vice versa. For example, if I have numbers 1-5, I want 5 to be worth the least and 1 to be worth the most. I can't seem to find something on this topic, so it's either impossible or, I just don't quite know how to phrase the search. Either way, I didn't want to be too specific so my question can be applicable to to others, but this is a coding question I am having issues with in my game.. Thanks in advance!
You can try sorting in descending order? If the numbers are in an array the following would sort them in that order:
var arr = [1,2,3,4,5];
arr.sort(function(a,b) {
return b - a;
});
You really need to be clear about what you mean by "worth less". Are you trying to make (1<5) evaluate to false? If so, there are much much better ways of doing it.
One trick though -- you can just multiply everything by -1.

Javascript: How do I code a script where the user inputs a number and it returns three other numbers?

I'm not even quite sure how I can make myself clear and I do apologize... but I have been searching all over the internet for a similar JavaScript code and I'm not even quite sure how to phrase the question ...
Basically, I want the user to input one thing, and I want something else to pop up.
As an example, the user would type in a number, let's say "10" into a text field or drop-down menu and then three other numbers would pop up, such as 15.25, 16.50, and 17.75 (either in pop window form, or just in a plain sentence, or in other text fields ... it doesn't really matter).
What I'm doing is I want to post an estimate calculator for loan payments on a website (with options for 30 day, 60 day, and 90 day payoff options).
There's no math involved in this code whatsoever (I understand if I have to input a lot of numbers - I already have those!). I don't want to create a calculator, because I think a calculator would be more complicated (I'm aiming for simple!) ... The loan fees and interest vary from one group of numbers to another, so if it were to be a calculator the script might get really complicated (because we're not looking at a easy 1 + 1 = 2 equation ... it's more like 1 + 1.50 + 1.00 = 3.50, or 10.00 + 4.00 + 1.25 = 15.25, or even 30.00 + 6.00 + 1.75 etc., there's no consistency).
So I'm figuring a simpler way around this beast would be to have the numbers readily available, with no calculations. So if they enter in a 1, the result they would get be 3.50, 4.50, and 5.50.
I don't know, that might be asking a bit much too....
Thank you in advance for your time and help.
In a simplest form it will look like this:
var magic_box = {
'1': [3.50, 4.50, 5.50],
'2': [2.50, 34.50, 5.55],
'3': [1.50, 0.50, 15.50]
};
var what = prompt( 'Tell me the magic number!' );
alert( magic_box[ what ] );
We use hash-map (aka javascript object) each element of which is an array, and each element of those arrays is your desired number.
Then, we give user a popup with question and store his answer (or his input) into variable.
Then we use this variable as a key for our hash-map.
p.s.: there are several issues with solutions above, so its purely for educational reasons.
building on #c69's answer, if there is a range for each set of numbers then add min, max values to the three numbers, loop through array, do an inclusion check, stop on row where number is in range

Is there a way to truncate scientific notation numbers in Javascript?

As you all know since it is one of the most asked topic on SO, I am having problems with rounding errors (it isn't actually errors, I am well aware).
Instead of explaining my point, I'll give an example of what possible numbers I have and which input I want to be able to obtain:
Let's say
var a = 15 * 1e-9;
alert(a)
outputs
1.5000000000000002e-8
I want to be able to obtain 1.5e-8 instead, but I cannot just multiply by 10e8, round and divide by 10e8 because I don't know if it will be e-8 or e-45 or anything else.
So basically I want to be able to obtain the 1.5000002 part, apply toFixed(3) and put back the exponent part.
I could convert into a string and parse but it just doesn't seem right...
Any idea ?
(I apologize in advance if you feel this is one of many duplicates, but I could not find a similar question, only related ones)
Gael
You can use the toPrecision method:
var a = 15 * 1e-9;
a.toPrecision(2); // "1.5e-8"
If you're doing scientific work and need to round with significant figures in mind: Rounding to an arbitrary number of significant digits
var a = 15 * 1e-9;
console.log(Number.parseFloat(a).toExponential(2));
//the above formula will display the result in the console as: "1.50e-8"

Categories

Resources