0

I have this line of equation in my JavaScript code.

Y= M*X + C
Y= -0.001*(X) + 4.1

My value for Y should be 2 at maximum, meaning my X input should be 2000 at max. However, I could not set the limit of X to 2000 as I would need the actual value of X for later calculation.

How can I fix Y at 2 if my X is more than 2000?

This is my code in javascript

document.getElementById("Result").innerHTML = (-0.001*(x) + 4.1);
NoobProgrammer
  • 474
  • 4
  • 21
  • 1
    If your `Y` needs to be at most `2`, use `Y = Math.min(2, -0.001 * X + 4.1);`, or `Y = -0.001 * Math.min(2000, X) + 4.1`, if `X` needs to be at most `2000`, or the option with the ternary expression below. – Sebastian Simon May 03 '18 at 07:50
  • 2
    `Y = (X > 2000) ? 2 : M*X+C;` – jsheeran May 03 '18 at 07:51
  • The coefficient of X is negative so values of X greater than 2000 are not the problem, values of X less than 2100 are: `-0.001*2100+4.1=2`. The correct solution is `Math.min(-0.001*X+4.1,2)` – Nick May 03 '18 at 08:01
  • @Xufox i dont understand what you guys mean, i have updated my question showing how i display the result pls check. Thanks – NoobProgrammer May 03 '18 at 08:13
  • @jsheeran i dont understand what you guys mean, i have updated my question showing how i display the result pls check. Thanks – NoobProgrammer May 03 '18 at 08:13
  • @Nick i dont understand what you guys mean, i have updated my question showing how i display the result pls check. Thanks – NoobProgrammer May 03 '18 at 08:13
  • @Nick i have tried and it is worked but this is not what im looking for, if my X is lesser than 2000 it will just display the value 2 – NoobProgrammer May 03 '18 at 08:15
  • What I was saying is that for the formula you have given, Y will be greater than 2 if X is less than 2100 (not > 2000, as you stated in your question). What @Xufox and I were both saying is that to make sure Y is never greater than 2, you should use `Math.min` which will ensure the value of Y is equal to the formula if the result is <2, or 2 otherwise. – Nick May 03 '18 at 08:47
  • @Nick ok thanks i have used your method and it work!! Thanks alot!!! – NoobProgrammer May 03 '18 at 09:45
  • Great to hear. Thank @Xufox too as he commented it first. – Nick May 03 '18 at 10:03
  • @Xufox Thanks for your help bro!! – NoobProgrammer May 03 '18 at 10:10

2 Answers2

0
Y= M*X + C
Y= -0.001*(X) + 4.1

You can add condition after Y calculation and change value of Y.

Y = Y > 2 ? 2 : Y

Or you can add condition directly on X

Y = X > 2000 ? 2 : (M*X + C) 

so according to your value

Y = X > 2000 ? 2 : (-0.001*(x) + 4.1)

document.getElementById("Result").innerHTML = Y;
Nirali
  • 1,776
  • 2
  • 12
  • 23
0
<script>
var Y = Math.max((-0.001*(Length * Width) + 4.1),4);
<script>
NoobProgrammer
  • 474
  • 4
  • 21