Forum Moderators: open

Message Too Old, No Replies

Random Currency

How do I randomly generate currency values

         

humpg

5:53 pm on Jul 31, 2007 (gmt 0)

10+ Year Member



I am creating math drills and the one I am on now has to do with calculating change for money.

I need to create a function that will randomly select a number between say $1.00 and $99.99 including the cents portion, and then subtract that number from $100.00 and get a result.

I have used random number generators in the past but can't get my head around how to do this for currency values.

If you have a script could you please give a brief explanation as well in case I don't understand it, I'm a newbie when it comes to js.

Trace

7:29 pm on Jul 31, 2007 (gmt 0)

10+ Year Member



Fun fun. How's this?
<script type="text/javascript">
// get random numbers and round to integers
var randomDollars= Math.floor(Math.random()*100);
var randomCents= Math.floor(Math.random()*100);

// convert string to number
var randomMonies= parseFloat(randomDollars + '.' + randomCents);

// substract random number from 100 and round to 2 decimals
var result= Math.round((100-randomMonies)*100)/100;

// output result
document.write('$100.00 - $' + randomMonies + ' = $' + result);
</script>

humpg

5:34 pm on Aug 7, 2007 (gmt 0)

10+ Year Member



Ok, I actually found it easier to work in cents and to change it to dollors ( / 100 ) when displaying results to the user.

Now the only problem I am having is when the user inputs their answer. Obviously they wouldn't be inputing it in cents so I have to convert there answer back to dollars by multiplying by 100. I thought it would be simple and thought I had it working until I came to this random question:

1000 - 180 = 820 which is displayed to the user as $10.00 - $1.80 and the user would input thier answer as 8.20

then I take that number and multiply it by a 100

userAnswer[questionNum] = parseInt(document.getElementById('answerBox').value * 100);

but the actual result I get is 819 (truncated from parseInt) when I multiply.

I have been doing research to try and solve this but some of the stuff I read that is talking about floating point numbers gets kind of confusing.

I have also found javascript calculators that give the wrong result and the the right result.

So, how do they get this simple arithmetic right with js?

humpg

1:26 pm on Aug 8, 2007 (gmt 0)

10+ Year Member



this worked for my problem of 820 coming out as 819:

parseInt( Math.round(document.getElementById('answerBox').value * 100) );

or will this still give me incorrect results for other results?

The largest number range I would be working with is 10000 and 9999 which would be $100.00 subtract any number between $1.00 and $99.99