I was writing a formula in javascript to help me easily calculate the break even formula when trading stocks. The formula is to calculate the break even point is: ((shares x price)+commission)/(shares)
So for my code I wrote:
<script type="text/javascript" language="javascript" charset="utf-8">
function output(){
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
var value3 = document.getElementById('value3').value;
document.getElementById('result').innerHTML = ((parseInt(value1) * parseInt(value2)) + (parseInt(value3))) / (parseInt(value2));
}
</script>
However, when I run it I don't get the correct answer. For example, when shares = 20, price = 8.88 and commission = 10, it gives me the answer as 8.5, but the correct answer is 9.38.
Can anyone tell me where I went wrong, thanks.
You are calling parseInt instead of parseFloat, so you are losing the fractional parts for your numbers.
document.getElementById('result').innerHTML = ((parseFloat(value1) * parseFloat(value2)) + (parseFloat(value3))) / (parseFloat(value2));
A slightly terser way of doing it is to use the unary plus operator when you get each value:
var value1 = +document.getElementById('value1').value;
var value2 = +document.getElementById('value2').value;
var value3 = +document.getElementById('value3').value;
document.getElementById('result').innerHTML = ((value1 * value2) + value3) / value2;
That's because the price is being parsed as an integer. Integers can't have decimals, so it's rounded down to 8.
Use parseFloat instead of parseInt for the price.
使用parseFloat
代替parseInt
,当使用parseInt
您最终将获得(20 * 8 + 10) / 20
,而不是(20 * 8.88 + 10) / 20
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.