I have a Class that help me to keep a range of values, it consist in 3 columns named min, max and price. When the user give me a number (example quantity=5) I need to search all the prices that the quantity satisfy this rule:
quantity=5 min >= quantity AND max <= quantity
var quantity = Number(req.body.quantity);
var Range = Parse.Object.extend("PriceRange");
var query = new Parse.Query(Range);
query.limit(1000);
query.greaterThanOrEqualTo("min",quantity);
query.lessThanOrEqualTo("max",quantity);
When I make this the result is always 0 and I have a row that is min = 1, max = 10 and price = 10
What is wrong? Parse don´t let me do querys like that?
It looks like the inequalities are reversed.
query.greaterThanOrEqualTo("min",quantity); // means: min >= quantity
query.lessThanOrEqualTo("max",quantity); // means: max <= quantity
...constrains the query to find objects where the value of min is greater than quantity, and likewise for the other constraint.
Those two constraints together present an impossible condition: where some number is both smaller than some small number and larger than some large number. Fix by reversing...
query.lessThanOrEqualTo("min",quantity); // where min <= quantity
query.greaterThanOrEqualTo("max",quantity); // where max >= quantity
Related
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 have the code below but I'm having issues when the dollar amount has commas, for example $1,234.56. When I use the code below, it spits out 0.00. It should show the new subtotal with comma(s) if it's over a thousand.
var subtotal = $('.divWithAmount').text().replace("$",""); // Get the subtotal amount and remove the dollar sign
var discount = subtotal * 0.2; // Multiply the amount by 20%
var newSub = subtotal - discount; // Calculate the new subtotal
var newSubtotal = newSub.toFixed(2); // Show only the last two numbers after the decimal
console.log(newSubtotal);
Thanks for your help!
The main reason it doesn't work is that the returned value from $('.divWithAmount').text() is of type String
To do operations it needs to be a number, and to enable that you also need to remove the comma and then parse it with e.g. parseFloat().
var subtotal = parseFloat($('div').text().replace("$","").replace(",",""));
var discount = subtotal * 0.2; // Multiply the amount by 20%
var newSub = subtotal - discount; // Calculate the new subtotal
var newSubtotal = newSub.toFixed(2); // Show only the last two numbers after the decimal
console.log(parseFloat(newSubtotal).toLocaleString());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>$51,234.56</div>
As commented, I updated my answer with toLocaleString, so the comma gets added back.
Here is a couple of ways how to localize the end result:
- Javascript Thousand Separator / string format
- Add thousands separator to auto sum
- convert a JavaScript string variable to decimal/money
to get number out of string value just do like this
var amount = "$1,234.56";
var doublenumber = Number(amount.replace(/[^0-9\.]+/g,""));
once you get number then you can perform operation you want and it will resolve your issue that you are facing.
I am using a function in my code that takes and does math with a value from a text box that the user writes in and also a calculated value that is used earlier in the page. If the text box value is not a positive number an alert will appear showing that the value must be a positive number. If it is a positive number, it shows an alert with the outcome of the math. The only problem is, when this happens, what appears is where the number should be there is instead "NaN". I believe this is because the values I'm using aren't actually numbers but I'm not sure how to fix this.
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = (total / 1000) * 0.621371;
document.getElementById('total').innerHTML = total;
}
function calc_gallons() {
var total = parseInt(document.getElementById("total").value)
var averagempg = parseInt(document.getElementById("averagempg").value);
var gallons = 0;
if (averagempg > 0) {
gallons = total / averagempg
window.alert("This trip requires " + gallons + " gallon(s). Have safe travels!");
}else {
window.alert("Your average MPG must be a positive number in order to calculate the gallons required for this trip.");
}
}
#this is the text box and the button that does the function
<p>Your Average MPG:<input type="text" id="averagempg" name="MPG"></p>
<button type="button" name="Calculate" onclick="calc_gallons()">Calculate!
Better use explicit type conversion:
var total = Number(document.getElementById("total").value);
var averagempg = Number(document.getElementById("averagempg").value);
parseInt then called on empty string ('') returns NaN.
If the first character cannot be converted to a number, parseInt
returns NaN.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
Examples: https://coderwall.com/p/kwhkig/javascript-number-conversion
The problem is getting total inside calc_gallons(). You're trying to get it from value, but you have it in a span. So either put total in a disabled input, or get it via innerHTML:
var total = parseInt(document.getElementById("total").innerHTML);
Are you sure you used the console? I failed to see the issue at first, and the following revealed that total is NaN:
console.log("total:", total, typeof total);
console.log("averagempg:", averagempg, typeof averagempg);
I've got a javascript function that adds one to a quantity if the current value is less than another value. Here is the javascript function:
function addQty()
{
if(document.getElementById("quantity").value < document.getElementById("stock").value)
document.getElementById("quantity").value++;
else
return;
}
And here are the form elements that the values are taken from:
<input type='text' id="quantity" name='quantity' value ='0' />
<input type='hidden' id="stock" name="stock" value="<?php echo $adjustedStock; ?>" />
So basically the user can add one to their quantity of a product to order only if there is enough in stock.
Now, this works absolutely fine if the number in stock is 1-9, but if the stock level is in double digits, the maximum the user can add to their basket (ie the 'quantity' in the code) returns as the first digit + 1. So if the stock is 13 then the max quantity is 2, or if the stock is 63 the max quantity is 7.
I've tried converting the integer value of $adjustedStock to a string before it is used in the form as I read sometimes browsers can behave weirdly in this situation, but this didn't work. Any ideas why this is happening?
Thanks in advance!
The "value" attribute of an <input> is always a string. Thus your comparison is being done between two strings, which is not what you want.
Convert the values to numbers before comparing:
function addQty()
{
var qtyInp = document.getElementById('quantity'),
qty = parseInt(qtyInp.value, 10),
stk = parseInt(document.getElementById('stock').value, 10);
if (qty < stk)
qtyInp.value = qty + 1;
}
Form element values are strings. Use parseInt or convert to a number some other way.
You can use Math.min() for this purpose...
function addQty() {
var quantity = document.getElementById("quantity");
quantity.value = Math.min(+quantity.value + 1,
document.getElementById("stock").value);
}
This makes it very clear that you want the lesser of the incremented quantity or the total in stock.
I'm creating a product page that requires the price to update when the quantity value is changed. Two form fields are used: .orig_price and #quantity. These values are obviously multiplied together.
I'm trying to split the multiplied value, so that I can print the correct format (27.7043454575 should be 27.70).
My code:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = jQuery(".orig_price").val().substr(1);
var qty = jQuery("#quantity").val();
// calculate price
var sumValue = origprice * qty;
// split price
var splitprice = sumValue.split(".");
var pricepound = splitprice[0];
var pricepenny = splitprice[1].substring(0,2);
// update price
jQuery("#pricediv").html('£' + pricepound + '.' + pricepenny);
jQuery("#pricediv").fadeIn(1500);
});
If I remove the split and use sumValue everything works (but format is wrong). Does split not work on a calculation?
You'll want to use sumValue.toFixed(2)
var sumValue = 27.7043454575;
sumValue.toFixed(2) // 27.70
.split does not exist on numeric types. You would have to use sumValue.toString().split('.'), and either way, this would be more inconvenient than simply sticking to .toFixed
You can use toFixed and parseInt() like so:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = parseInt(jQuery(".orig_price").val().substr(1),10);
var qty = parseInt(jQuery("#quantity").val(),10);
// calculate price
var sumValue = origprice * qty;
// split price
var price = sumValue.toFixed(2);
// update price
jQuery("#pricediv").html('£' + price);
jQuery("#pricediv").fadeIn(1500);
});
toFixed determines the number of points after a decimal, and parseInt type-casts the input to an integer (the 10 is unnecessary but there to show it's decimal base 10), because when getting data from a form field it sometimes comes back as a string and messes up your math.