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 last month.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
Improve this question
i am tryin to calculate profit percentage from day to day , for example :
yesterday i sold 10 items , today i sold 5 items , so the percentage must be -50% .
I've managed to make the progress but i believe i still missing something in my calculation .
My table snapshot :
when the sold items of past day is 0 the progress become infinity .
here is my javascript code :
var class_name = ( parseFloat(row.total_sold) > parseFloat( row.prev_total_sold ) ? `success` : `danger` ) ;
class_name = ( parseFloat(row.total_sold) == parseFloat( row.prev_total_sold ) ? `primary` : class_name) ;
class_name = ( row.prev_total_sold == null ? `primary` : class_name) ;
var percentage = ( ( (row.total_sold - row.prev_total_sold) / row.prev_total_sold) * 100).toFixed(1);
return `<span class="badge badge-light-${class_name} ">
<i class="fa-solid fa-arrow-trend-up text-${class_name}" style="padding-right : 5px"></i>
${percentage}%
</span>`
Row query :
prev_total_sold = is the value of sold items from past day
total_sold = is total sold items of current day
the question is : is my calculation good for the requirements ? and why i am getting infinite value when today sold is 0 !
The problem here seems to be a mathematical problem: how many times do you have to multiplicate 0 to get 5? The answer is infinity.
My suggestion here is to check if prev_total_sold is 0 then use a default value like +100%.
Modified code:
var percentage = row.prev_total_sold ? ( ( (row.total_sold - row.prev_total_sold) / row.prev_total_sold) * 100).toFixed(1) : '100.0';
You are getting infinity, because of the underlying math. Assigning a percentage for a growth from 0 to y (with y > 0) would mean there is some x such that the following equation is fulfilled
0 * x = y
And there can't be such x because 0 * something is always zero.
Displaying infinity is the next best thing that happens when you divide by zero in javascript. Other languages may throw an exception. If you want to display any other special value instead of infinity, you should check if prev_total_sold === 0 first before dividing ...
var percentage = prev_total_sold === 0
? (total_sold === 0 ? "0.0" : "some default value")
: (((row.total_sold - row.prev_total_sold) / row.prev_total_sold) * 100).toFixed(1);
Related
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 3 years ago.
Improve this question
I've been struggling with the definition of a function. It must take a positive number N as a parameter and return the last ordered number. By "ordered" number I mean that every digit follow each other.
Example1 : Takes 1000 as a parameter and returns 789.
Example2 : Takes 500 as a parameter and returns 456.
Here's working code. Although I don't like just giving you the answer. This is something you have to practice and learn how to do on your own. Take the time to understand what I did. Also, this solution can be improved a lot, just something that I did quickly and works.
The algorithm in action:
function calc() {
//Get the number in the text input
var nbr = parseInt(document.getElementById("number").value, 10);
//Loop starting from the top
for (var i = nbr; i > 0; i--) {
if (isOrderedNumber(i)) {
document.getElementById("result").innerText = i;
return;
}
}
document.getElementById("result").innerText = "None found";
}
function isOrderedNumber(number) {
var digits = number.toString().split('');
//Loops in the digits of the number
for (var i = 0; i < digits.length - 1; i++) {
//Check if the current number+1 is not equal to the next number.
if (parseInt(digits[i]) + 1 !== parseInt(digits[i + 1])) {
return false;
}
}
return true;
}
<input id="number" type="text" />
<button onclick="calc()">Find last ordered number</button>
<br/>
<br/>
<span id="result"></span>
In you case, instead of using html element you would receive "nbr" by parameter instead and would return the value instead of putting the value in the html element. Ask if you have any questions on how this works.
i have a MYSQL database where i want to sort the totals of both paind and unpaid amounts. The Query i used was :
SELECT DISTINCT
YEAR( app_payments.created_at ) AS YEARS,
SUM( app_payments.amount ) AS Total,
app_users.serial,
app_payments.`status` AS payment_state
FROM
app_payments
INNER JOIN app_users ON app_payments.created_by = app_users.serial
WHERE
app_payments.created_by = 'd88faa'
GROUP BY
YEAR ( app_payments.created_at ),
app_payments.status
i got the results as:
2017 1995 d88faa 1
2018 1200 d88faa 1
2019 1250 d88faa 0
2019 4990 d88faa 1
Where 1 stands for PAID and 0 stand for UNPAID
in my php code, i tried to group the data into years
$Stats = array ();
while(!$this->EndofSeek()){
$result = $this->Row();
if($result->payment_state == 0 ){
if(in_array($result->YEARS,$Stats)){
array_replace($Stats,['y'=>$result->YEARS , 'b'=>$result->Total ]);
}else{ array_push($Stats,['y'=>$result->YEARS , 'a'=>0 , 'b'=>$result->Total ]);}
}else if($result->payment_state == 1){
array_push($Stats,['y'=>$result->YEARS , 'a'=>$result->Total , 'b'=>0 ]);
}
}
return json_encode($Stats)
This returns the output:
[{"y":"2017","a":"1995","b":0},
{"y":"2018","a":"1200","b":0},
{"y":"2019","a":"4990","b":"1450"},
{"y":"2019","a":"4990","b":0}]
Where y is YEARS , a is PAID and b is UNPAID
What i seek to achieve is to group all the data to a particular year where i would have
[{"y":"2017","a":"1995","b":0},
{"y":"2018","a":"1200","b":0},
{"y":"2019","a":"4990","b":"1450"}]
Without it duplicating the year but rather merging them into a single unit.
What do i need to do, and which code do i need to implement to achieve this.
Do you just want conditional aggregation?
SELECT YEAR(p.created_at) AS YEAR,
SUM( CASE WHEN p.status = 0 THEN p.amount END) AS Total_0,
SUM( CASE WHEN p.status = 1 THEN p.amount END) AS Total_1
FROM app_payments p INNER JOIN
app_users u
ON p.created_by = u.serial
WHERE p.created_by = 'd88faa'
GROUP BY YEAR(p.created_at);
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 5 years ago.
Improve this question
I am asked the following questions and came up with a solution but I can't seem to figure out how the other conditions are met or satisfied.
function scoreTest(correct, questions) {
var percent;
// Only change code below this line
percent = (correct*questions); // My logic
// Only change code above this line
return percent;
}
// Change the inputs below to test your code
scoreTest(18,20);
scoreTest(20,25) should return a number //Output met
scoreTest(47,50) should return a value of 94
scoreTest(16,20) should return a value of 80
scoreTest(8,10) should return a value of 80 //Output met
scoreTest(97,100) should return a value of 97
scoreTest(1,50) should return a value of 2
You are so close. Percentages are calculated like this (numberCorrect / TotalQuestions) * 100. This will give you a percentage value.
Given this, re-factor your function to output a percentage:
function scoreTest(correct, questions) {
var percent;
// Only change code below this line
percent = (correct/questions) * 100; // Actual percentage value
// Only change code above this line
return percent;
}
// Change the inputs below to test your code
scoreTest(18,20);
scoreTest(20,25) //should return a number //Output met
scoreTest(47,50) //should return a value of 94
scoreTest(16,20) //should return a value of 80
scoreTest(8,10) //should return a value of 80 //Output met
scoreTest(97,100) //should return a value of 97
scoreTest(1,50) //should return a value of 2
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 ;-)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript’s Math broken?
from this question:
get all the input value and make an addition
there is a promotion:
buy 1 each price is 14.37, buy 10 the price is 13.28, buy 20 each price is 10.78.....
now i want to do a counter.http://down123.xxmn.com/count.htm
the counter write the whole price.now, there is something wrong with my code.
if i fill 5 in an input box, then fill 5 in another input box. the whole price isn't 132.8. why?
if i remove a number in an input box, the whole price doesn't change. thank you
the code:
var $inputs = jQuery('.liste_couleur_qty li input');
$inputs.keyup(function() {
var result = 0;
$inputs.each(function(){
result += parseInt(this.value, 10);
});
var JsonData =[{"price_id":"1","website_id":"0","price_qty":1,"price":"14.37"},
{"price_id":"2","website_id":"0","price_qty":10,"price":"13.28"},
{"price_id":"3","website_id":"0","price_qty":20,"price":"10.78"},
{"price_id":"3","website_id":"0","price_qty":50,"price":"9.23"},
{"price_id":"3","website_id":"0","price_qty":100,"price":"7.91"}
]
var sorted = JsonData.sort(function(a,b){return a.price_qty - b.price_qty;});
var i=0;
while(i < sorted.length && sorted[i].price_qty <= result){i++;}
var price = sorted[i-1].price;
price= price*result;
jQuery('#qtyvalue').html("Total price is " + price);
});
now, when the qty is 9, the right price is 9*14.37. but my counter is not right.
The answer you are looking for is a method called .toFixed()
Try changing the last line that sets your price to
jQuery('#qtyvalue').html("Total price is " + price.toFixed(2));
and that should work.
Update:
When you empty any text box, your code stops working since the value is '' rather than 0, and can't be added. Update the 5th line of the code to this:
result += parseInt((this.value === '' ? 0 : this.value), 10);