Reputation: 21
I'm having trouble, I'm a new programmer (obviously) and I was wanting to make a wallet program to keep track of my money since I don't have a bank account. I want my money to add up correctly, but it just combines the words. Also I wanna know how to store that number, so when I leave and come back it'll be the same number.
Heres my code: (Very bad and prototype)
<HTML>
<HEAD>
<TITLE> JavaScript Wallet </TITLE>
</HEAD>
<BODY>
<h2>Wallet</h2>
<script language="Javascript">
var plusCash = prompt("How much money are you entering?");
var money = 0.00;
var money = money + plusCash;
document.write("You have $" + money);
</script>
</BODY>
</HTML>
Upvotes: 0
Views: 687
Reputation: 155045
To persist values between pages and browser sessions, you can use either cookies for short simple values, or localStorage
, which was introduced in the HTML5-wave of platform enhancements.
Cookies would not be ideal in this situation because I'm guessing you're using HTML files on disk, therefore localStorage
would be better.
localStorage
is used thusly:
window.localStorage['someValue'] = someOtherValue;
localStorage
can only store strings, not complex types (objects). You must 'stringify' / serialize them first, but this is easy:
window.localStorage['someObject'] = JSON.stringify( someObjectValue );
Note this code requires a fairly modern browser (think IE10, Chrome or recent builds of Firefox).
Upvotes: 2
Reputation: 41958
Since prompt
returns a string
value, 'adding' that to a float results in a string - Javascript implicitly converts the float since it gives least data loss. To treat plusCash
as a float
value, invoke parseFloat
on it:
var money = money + parseFloat(plusCash);
Upvotes: 4