Javascript Tofixed Decimal Places Doesn't Work
What's the error in my script? It must have something do to with tofixed, not sure if it's the right place where it should be? The rounding seems like to not work. Still having en
Solution 1:
You're calling toFixed
on the result of parseFloat(value3)
, and then using that as the right-hand operand of *
— turning it back into a number again. Then you're taking the number resulting from the multiplication and assigning it to innerHTML
, which turns it into a string using the default toString
.
You probably meant to apply toFixed(2)
to the overall result:
document.getElementById('result1').innerHTML = ((parseFloat(value1) + parseFloat(value2)) * parseFloat(value3)).toFixed(2);
// --------------------------------------------^--------------------------------------------------------------^
functionoutput() {
var value1 = document.getElementById('value1').value;
var value2 = document.getElementById('value2').value;
var value3 = document.getElementById('value3').value;
document.getElementById('result1').innerHTML = ((parseFloat(value1) + parseFloat(value2)) / parseFloat(value3)).toFixed(2);
}
<inputid="value1"type="text"onchange="output();" /><span> + </span><inputid="value2"type="text"onchange="output();" /><span> / </span><inputid="value3"type="text"onchange="output();" /><pid="result1"></p>
Post a Comment for "Javascript Tofixed Decimal Places Doesn't Work"