I have the following script to calculate inventory values. However, it is rounding to the nearest whole integer without decimal as opposed to two decimal places. The output is formatted correct, but I believe the issue starts with the way the inputs are read into the JS. The input form is formatted all ready to accept decimal values. Calculations work correctly, but can't output with decimal. I appreciate any help!
function EI() {
var cost,
BItotal,
TPtotal,
TStotal,
total1,
total2,
total3;
cost = 1;
BItotal = document.getElementById(''InputBI'').value;
TPtotal = document.getElementById(''InputTP'').value;
TStotal = document.getElementById(''InputTS'').value;
total1 = cost * parseInt(BItotal);
total2 = total1 + parseInt(TPtotal);
total3 = total2 - parseInt(TStotal);
document.getElementById(''total_cost'').innerHTML = total2.toFixed(2);
HTML read out is below:
<input onclick="EI();" type="button" value="Calculate"/><p id="total_cost"></p>
Don't use parseInt()
when you want a floating point number, use parseFloat()
.
parseInt()
will round up your decimals automatically to create an Integer
output of the value you sent.
parseFloat()
"Parses a string argument and returns a floating point number." -MDN
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.