Forum Moderators: open
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.
<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>
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?
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