EDIT
I tested something out, and apparently, this:
if(info.max.value == "") {maxdesiredvalue = 999999999999999999999}
Returns in the chrome console:
> maxdesiredvalue
< 999999999
So I believe the problem really comes from there... is there a maximum number of digits we can attribute to a variable?
I'm into javascript for a few months now, and I've made a program that generates random weapons for a tabletop rpg.
Every weapon generated has a price relative to it's attributes. My problem today is that this price won't exceed 9 digits (cannot reach billion), even though it can.
In my generator, it is possible to choose certain properties before generating the weapon. If I intentionally try to generate something worth over a billion gold, it will crash instantly. On the other hand, if there is any way the weapon can be generated without exceeding the billion, it will do so.
For example, the most expansive metal is the "Residuum". The only 2 weapons that can be generated in Residuum are the dart and the shuriken, since they only use 1/16 of an Ingot. Therefore if I set the metal to be Residuum, they will be the only 2 possible generated weapons. From this point, if I try to specify I want a Residuum Sword, it will simply crash as explained earlier.
In my generation options, I also have a text input for the user to choose a minimum value and/or a maximum value for the weapon. I set the default max value to Infinity, so it should'nt be a problem.
function desiredvalue(){
if(info.max.value == "") {maxdesiredvalue = Infinity}
else {maxdesiredvalue = parseInt(info.max.value)}
if(info.min.value == "") {mindesiredvalue = 0}
else {mindesiredvalue = parseInt(info.min.value)}
}
In my html:
Min price: <input type="text" name="min" value="" onchange="desiredvalue()">
Max price: <input type="text" name="max" value="" onchange="desiredvalue()">
I already tried to deactivate this function to see if it was the problem, but even without a specific max value, weapons still won't be generated if their value exceeds 9 digits.
Maybe the problem sets inside the value formula, so here it is, even though it might not be a big help since it is all made up from variables.
WeapValue = ((((IngotValue * Ingots) + CraftTime + (actualEnchantTime * 3) + (LS * 0.02) + (R * 0.05) + BS + (FTH * 0.03)) * (((BPArace + BPAstatus + BPAlevel + ((BPAcrit1 + 1) * BPAcrit2)) / 100) + 1)) + PAenchant + PAaugment1 + PAaugment2 + PAaugment3)
Also the value is modified afterwards to fit in gold, silver or copper...
WeapValue.toLocaleString('en-US', {minimumFractionDigits: 0});
WeapValue = WeapValue.toFixed(2);
if (WeapValue >= 2) {WeapValue2 = Math.ceil(WeapValue); goldtype = " GP"}
else if (WeapValue < 2 && WeapValue >= 1) {WeapValue2 = WeapValue * 10; goldtype = " SP"}
else if (WeapValue < 1 && WeapValue >= 0) {WeapValue2 = WeapValue * 100; goldtype = " CP"}
Nothing else in the script really change the value, and all the variables affecting it are defined earlier, and I don't really think they are the problem, since they actually seem to work (they simply make the price exceed 9 digits).
If you have any questions related to the script, I'm here to answer, but I can't put the full script since it is very, very long (2543 lines)...
If anyone has an idea of how I can deal with my problem, it would be so appreciated! Again, I'm not a javascript expert, but I did my best and looked a lot on the Internet for help, but I still can't get rid of this problem...
Thank you!
Related
well... for begining, i m building some dumb and easy projects because i'm starting learning the world of front end development. One of those you can find in internet was this Color picker idea. Some page where with a button you can generate a random color. all random, no connections between the colors o something else.
(i'm not a native english speaker so sorry if i write something and you dont get it right)
Here's the link to the repository
so...
I build a function that makes a random HSL color randomizing the values and then building a string and puting that in the css
function getRandomHsl(){
let hueValue = 0;
hueValue = Math.floor(
Math.random() * (360 + 1)
)
let satValue = 0;
satValue = Math.floor(
Math.random() * (100 + 1)
)
let lightValue = 0;
lightValue = Math.floor(
Math.random() * (100 + 1)
)
return 'hsl(' + hueValue + ', ' + satValue + '%, ' + lightValue + '%)';}
if you can give me your opinion on that function and tell me if you would have done it inanother way.
so... i wanted to find the way to if the Lightness would have a low value the color of the font change it to some white or something like that. And this is what i figured out. (the first part of the code is the button changing the value of the background color of the main div. This works well. The problem comes after).
hslBtn.addEventListener('click', () => {
let hslStringComplete = getRandomHsl();
colorShowcase.textContent = hslStringComplete;
document.getElementById('color-container').style.backgroundColor = hslStringComplete;
/*================================= change the color font od the text when its to dark */
let hslLightValue = hslStringComplete;
let lightValue = hslLightValue.toString().substr(13,3).replace(/\D/g,'')
console.log(hslLightValue.substr(13,3).replace(/\D/g,''));
if(lightValue < 40){
innerHTML('input').style.color = "white";
}})
i have really strougle it out coming up with this idea so i want some opinion on how could i have done in other way.
PD: `if(lightValue < 40){
innerHTML('input').style.color = "white";}
this is hte HTML: <input class="background-container"><h3 class="forWhiteColor">Background Color : <span class="color-showcase">#messi</span></h3></input>
this part get me an error and the html doesn get changes. Here's the error.
console error
thanks in advance.
innerHTML('input') should probably be document.getElementById('color-container') instead.
also you should note that when you extract a part of a string, you get a string.
And comparing a string to a number won't work well, you first need to convert your string to a number with parseInt (for integers) or parseFloat (for float)
I'm writing a basic random number generator (self teachingvia freeCodeCamp, going to use it for games with my 2 little boys). I'm using a basic HTML with no CSS added as the DOM and Javascript client side for the function (client side as my eldest is 5 and we have a family blog he loves to show people).
The problem is that the code below is working to a point - the Math random function is fine, it works with Math.floor well and the multiplcation * (maximum - minimum +1) is all working as expected.
The issue is that the last segment is not working: + minimum. From the results I have looked at the formula is generating a result up to and including the multiplcation bracked, but then concatenating the minimum on the end, rather than adding it to the result.
I have converted the maximum and minimum values to integers via parseInt when I first discovered the problem, in case there was an issue there (I didn't see why as they both worked fine in the multiplcation bracket), but that of course made no difference.
function randomNumberFunction(maximum, minimum) {
var numRan;
var maximum = document.getElementById("maximum").value;
var minimum = document.getElementById("minimum").value;
parseInt(maximum);
parseInt(minimum);
numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
alert(numRan);
}
<div id="dice">
<form name="randomDice">
<h1>Get a random number</h1>
<p>Maximum</p>
<input id="maximum" type="number" name="random"><br>
<p>Minimum</p>
<input id="minimum" type="number" name="random"><br>
<br>
<button onclick="randomNumberFunction()">Get a random number</button>
</form>
</div>
I'm looking to be able to capture the minimum and maximum values a user inputs, and produce a random integer from that range. Instead I get values like 01 when I input min 1, max 4, or 21. or 63 when inputting min 3, max 10.
You aren't assign value when you cast minimum and maximum variables
Try this:
function randomNumberFunction(maximum, minimum) {
var numRan;
var maximum = document.getElementById("maximum").value;
var minimum = document.getElementById("minimum").value;
maximum = parseInt(maximum);
minimum = parseInt(minimum);
numRan = Math.floor(Math.random() * (maximum - minimum + 1)) + minimum;
alert(numRan);
}
I'm trying to calculate the EMA with this script.
But it does not give me the correct EMA.
This could be of many reasons, but i'm not sure what it is.
I've tried different formulas for the EMA without any better results, I'm really not a professional coder nor mathematician and thus i can't see what I'm doing wrong.
How Is the EMA value calculated over time? For the first value I calculate the first EMA using the SMA, i guess that should work - right?
My EMA value = 0.033144798412698406
Real EMA value = 0.033084
Close = last closing price
Period = 20;
Multiplier = (2 / (period + 1));
function calculateEMA() {
if (EMA == 0) {
EMA = (Close - SMA) * multiplier + SMA;
calculateEMA();
} else {
for (a = 0; a < period; a++) {
EMA = (Close - previous_ema) * multiplier + previous_ema;
console.log(EMA + " ema");
previous_ema = EMA;
}
}
}
// UPDATE Added my whole script (which can be runned)- https://pastebin.com/91GEuATM
You need Nodejs and the binance node api installed (npm install node-binance-api --save) ; Keep in mind that this is just my "test script" hence all the weird variable names etc.
//UPDATE 2 Ticks sample data https://pastebin.com/AFzf7GwQ
I got the function setup and variables taken care. I am trying to calculate taxi fare per start zone, end zone and elapsed time.
Here what I have so far but it is not calculating well.
It keeps giving me $5
if( startZone == 1 && endZone == 1 ){
totalTaxiFare = baseCharge;
if( timeCovered > 0 && timeCovered <= 4 ){
baseCharge = 5.00;
charge = (0.75/timeCovered)*timeCovered;
totalTaxiFare = baseCharge + charge;
}
}
if( startZone == 1 && endZone == 2 ){
totalTaxiFare = baseCharge;
if( timeCovered > 4 && timeCovered <= 10 ){
baseCharge = 7.00;
charge =( 3.00 + (0.50 * ( timeCovered - 4 ) * ( 0.75 / timeCovered ) * timeCovered ) );
totalTaxiFare = baseCharge + charge;
}
}
document.writeln("<p> The total taxi fare is $" + totalTaxiFare + "</p>");
Ok, I don't know if I got the math correctly since I had to guess what the rates were by looking at the pattern. There's that zone thing I'm not sure what that's about, but by looking in the original code, I think it's a conditional to change the calculations for working 2 shifts?
Anyways, you should always use var for your variables, otherwise all of that data is floating around in globalspace. You had this expression: totalTaxiFare = baseCharge; floating around being exposed. So it looks as if ultimately your totalTaxiFare was constantly being changed to baseCharge which is at a constant value of 5.00. If you used var and kept the majority of your variables local, you'd probably get different results, but with the expressions you had those results wouldn't be accurate.
I'm definitely not a math wizard (lazy in high school), but is this an expression that would yield an appropriate result for cab fare?: `
(0.75/timeCovered)*timeCovered;
Ok, parenthesis first and we'll say 3 minutes? 3 hours? 3 time units I guess.
(.75/3)*3 which is (.25)*3 which is .75 so that was changed into a more appropriate expression:
(.75)*timeCovered;
So that would be
(.75)*3 = 2.25
Sorry if I sound harsh, I think that if you want to program, you should pay special attention to your math. Even if your syntax is flawless, it won't help if the math is even a little off.
Here's a DEMO, like I said before, I guessed as to how the expressions are done because you didn't provide the complete rates or given any details on time. It looks like it's working like it should give it a try. Good luck, sir ;-)
I am currently dabbling with JavaScript and am doing some simple calculations using for loops and I am attempting to take user info for the Table set they want and the numbers they wish to multiply between e.g.
Enter Table set: 12
Enter where to start multiplying from: 3
Enter how high to multiply: 6
This would print:
12 x 3 = 36
12 x 4 = 48
12 x 5 = 60
12 x 6 = 72
My issue is that when I ask the user to select how high they wish to multiply to, if they select a number greater than 9 it doesn't enter the for loop and prints nothing yet 9 and below works.
This is the simple enough code:
function UserEnteredTables()
{
var tableNumber = prompt("Please enter the number tables to use: ");
var numberLowerLimit = prompt("Please select where you want to start multiplying from: ");
var numberUpperLimit = prompt("Please select how high to multiply to: ");
document.write("Before the loop " + numberUpperLimit + "<br/>");
for (i = numberLowerLimit; i <= numberUpperLimit; i++)
{
document.write("Made it inside the loop " + "<br/>");
document.write(tableNumber + " * " + i + " = " + (i * tableNumber) + "<br/>");
}
document.write("After the loop " + numberUpperLimit);
}
Apologies for any indentation issues, had issues pasting for some reason
I have attached two images, one where I enter the upper limit to 9 and then one were I enter 10. As you can see the 10 doesn't enter the loop.
I assume that I have missed something very simple but I would appreciate if someone could explain what the issue is or if its something to do with JavaScript loops.
If there is something wrong with the post or you require some other code to fully understand just let me know.
Thanks in advance :)
The issue is with the prompt value returned: its typeof is string, while what you want is number for the loop to work correctly.
Use parse() to extract the numeric value out of the prompt value, see here:
https://jsfiddle.net/jwvj2aab/1/
Note that you will need to handle user input in order to deny anything but numbers