# Calculate interest earned code

Hello.

I’m a JavaScript newbie and need help with code.

Given principle, yearly interest rate and time in years, I need to calculate interest earned and the ending amount in the account at the end of time.

Formulas:
I=PRT
S=P+T

This is what I have which didn’t work:

<script type=“text/javascript”>
var P,R,T,I,S;

``````  P=prompt("enter your Principle","");
T=prompt("enter the time in years","");

I=P*R*T;
S=P+I;

document.write("Interest= "+P+"*"+R+"*"+T+"&lt;br /&gt;");
document.write("S= "+P+"+"+I+"&lt;br /&gt;");
``````

</script>

Thank you for the help.

It seems to work for me.

Are you entering only numeric numbers? 40000 is good, 40,000 is bad, and \$40,000 is also bad.

Can you show us a test web page that demonstrates it not working?

I finally got the Interest to multiply, but I can’t get the Summary to add up. It’s adding the Principle and Interest as 100100 when it should be 200.

<script type=“text/javascript”>
var P,R,T,I,S;

``````  P=prompt("enter your Principle","");
T=prompt("enter the time in years","");

I=P*R*T;
S=P+I;

document.write("Interest= " +P*R*T+"&lt;br /&gt;");
document.write("Sum of Account= " +(P+I)+"&lt;br /&gt;");
``````

</script>

That problem occurs because those variables are considered to be strings.

You can easily resolve that by ensuring that the prompted values are numbers instead.

As an example, here is how you can make P a number, and if it’s not, defaults to a value of 0.

``````
P = prompt("enter your Principle", "");
P = Number(P) || 0;

``````

Still confused…I’m not able to get the Sum of Account to add up. Sum= Principle + Interest.
The Principle+ Interest is not adding up, but it is joined together according to my document.write code. :headbang:

Show us your updated code, because there is something you’re not doing right.

You may also want to use the calculated variables for interest and sum of account in the document.write.

Another thin that will make your code a lot easier to understand, is to use variable names that are more expressive than single letter variables.

You may have heard that TINSTAAFL but have you heard that IWBMIWMBF?

As an example, instead of this:

``````
I=P*R*T;

``````

The following code is much more understandable:

``````
interest = principal * rate * years;

``````