Make large numbers worth less than small numbers (JS) - javascript

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.

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?

How do I sort an array of words that represent numbers?

How can we Sort numbers in words (one, two, three) in Javascript (Angularjs)
My array has some numeric words
$scope.Numbers = ["three", "one", "five", "two", ...... "hundred", "four"];
I want the result to be:
one
two
three
four
...
...
...
hundred
I have searched Google for the solution, but I have not found anything
Also i have tried array.sort(), but it is sorting alphabetically.
Here is a simple multi-step solution:
convert the words to numbers.
Sort the array with .sort(function(a,b){ return a-b; }).
convert the array back to words.
We effectively reduced the problem of sorting words to the problem of sorting numbers and the problem of converting numbers to and from words.
The greater picture is that by reusing the solutions of 3 smaller problems we solved a bigger issue. This is a fundamental part of programming anywhere and here in particular - by finding smaller subproblems and applying them to the task at hand we've solved it quickly and without ever having to actually implement a sorting function on words themselves.
Going to elaborate a bit on what people have written in the comments for you. Simply put, the compiler can't know which word is higher or lower than any other, since words are just a collection of chars. It's pretty much like saying: Which word has a higher value, "chicken" or "car"? Or how can the compiler know that you are even writing in English? What happens if you write the numbers in words but in other languages? Basically, to the compiler each string is a set of chars and it doesn't care which letters or words they are since it doesn't matter from its point of view. If you compare it to a number instead, a number is a legit structure which has properties and mathematical rules to follow. I believe this is the reason people are downvoting your question.
There is no basis for a sorting algorithm to start. Thus, you need to convert the strings to integers first, then sort them, and then convert them back to strings if you want to have them ordered - just like Benjamin above explained.

Purpose of dividing by 1 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)

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"

Javascript percentage validation

I am after a regular expression that validates a percentage from 0 100 and allows two decimal places.
Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript?
#Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters.
Thanks to all those who have replied so far. I have found the comments really interesting.
Rather than using regular expressions for this, I would simply convert the user's entered number to a floating point value, and then check for the range you want (0 to 100). Trying to do numeric range validation with regular expressions is almost always the wrong tool for the job.
var x = parseFloat(str);
if (isNaN(x) || x < 0 || x > 100) {
// value is out of range
}
I propose this one:
(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)
It matches 100, 100.0 and 100.00 using this part
^100(\.0{1,2})?$
and numbers like 0, 15, 99, 3.1, 21.67 using
^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$
Note what leading zeros are prohibited, but trailing zeros are allowed (though no more than two decimal places).
This reminds me of an old blog Entry By Alex Papadimoulis (of The Daily WTF fame) where he tells the following story:
"A client has asked me to build and install a custom shelving system. I'm at the point where I need to nail it, but I'm not sure what to use to pound the nails in. Should I use an old shoe or a glass bottle?"
How would you answer the question?
It depends. If you are looking to pound a small (20lb) nail in something like drywall, you'll find it much easier to use the bottle, especially if the shoe is dirty. However, if you are trying to drive a heavy nail into some wood, go with the shoe: the bottle with shatter in your hand.
There is something fundamentally wrong with the way you are building; you need to use real tools. Yes, it may involve a trip to the toolbox (or even to the hardware store), but doing it the right way is going to save a lot of time, money, and aggravation through the lifecycle of your product. You need to stop building things for money until you understand the basics of construction.
This is such a question where most people sees it as a challenge to come up with the correct regular expression to solve the problem, but it would be much better to just say that using regular expressions are using the wrong tool for the job.
The problem when trying to use regex to validate numeric ranges is that it is hard to change if the requirements for the allowed range is changes. Today the requirement may be to validate numbers between 0 and 100 and it is possible to write a regex for that which doesn't make your eyes bleed. But next week the requirment maybe changes so values between 0 and 315 are allowed. Good luck altering your regex.
The solution given by Greg Hewgill is probably better - even though it would validate "99fxx" as "99". But given the circumstances that might actually be ok.
Given that your value is in str
str.match(/^(100(\.0{1,2})?|([0-9]?[0-9](\.[0-9]{1,2})))$/)
^100(\.(0){0,2})?$|^([1-9]?[0-9])(\.(\d{0,2}))?\%$
This would match:
100.00
optional "1-9" followed by a digit (this makes the int part), optionally followed by a dot and two digits
From what I see, Greg Hewgill's example doesn't really work that well because parseFloat('15x') would simply return 15 which would match the 0<x<100 condition. Using parseFloat is clearly wrong because it doesn't validate the percentage value, it tries to force a validation. Some people around here are complaining about leading zeroes and some are ignoring trailing invalid characters. Maybe the author of the question should edit it and make clear what he needs.
I recomend this, if you are not exclusively developing for english speaking users:
[0-9]{1,2}((,|\.)[0-9]{1,10})?%?
You can simply replace the 10 by a 2 to get two decimal places.
My example will match:
15.5
5.4366%
1,43
50,55%
34
45%
Of cause the output of this one is harder to cast, but something like this will do (Java Code):
private static Double getMyVal(String myVal) {
if (myVal.contains("%")) {
myVal = myVal.replace("%", "");
}
if (myVal.contains(",")) {
myVal = myVal.replace(',', '.');
}
return Double.valueOf(myVal);
}
None of the above solutions worked for me, as I needed my regex to allow for values with numbers and a decimal while the user is typing ex: '18.'
This solution allows for an empty string so the user can delete their entire input, and accounts for the other rules articulated above.
/(^$)|(^100(\.0{1,2})?$)|(^([1-9]([0-9])?|0)\.(\.[0-9]{1,2})?$)|(^([1-9]([0-9])?|0)(\.[0-9]{1,2})?$)/
(100|[0-9]{1,2})(\.[0-9]{1,2})?
That should be the regex you want. I suggest you to read Mastering Regular Expression and download RegexBuddy or The Regex Coach.
#mlarsen:
Is not that a regex here won't do the job better.
Remember that validation msut be done both on client and on server side, so something like:
100|(([1-9][0-9])|[0-9])(\.(([0-9][1-9])|[1-9]))?
would be a cross-language check, just beware of checking the input length with the output match length.
(100(\.(0){1,2})?|([1-9]{1}|[0-9]{2})(\.[0-9]{1,2})?)

Categories

Resources