Reputation: 77
I have the following code:
Type a value in the Centimeter field to convert the value to Feet:
<p>
<label>Centimeter</label>
<input id="inputCentimeter" type="number" placeholder="Centimeter"
oninput="LengthConverter(this.value)"
onchange="LengthConverter(this.value)">
</p>
<p>Feet: <span id="outputFeet"></span></p>
<script>
function LengthConverter(valNum) { document.getElementById("outputFeet").innerHTML=valNum*0.0328084.toFixed(2);
}
</script>
On most inputs, the returns output has the right format, but on some given sizes (for example 155cm) it returns several decimals:
155 Cm=4.6499999999999995 Ft
Upvotes: 0
Views: 311
Reputation: 754
Just calculate the value first and then do the rounding up. To calculate the value first, put them inside the parentheses.
(valNum*0.0328084).toFixed(2)
Your code is modified below.
<p>
<label>Centimeter</label>
<input id="inputCentimeter" type="number" placeholder="Centimeter"
oninput="LengthConverter(this.value)"
onchange="LengthConverter(this.value)">
</p>
<p>Feet: <span id="outputFeet"></span></p>
<script>
function LengthConverter(valNum) { document.getElementById("outputFeet").innerHTML=(valNum*0.0328084).toFixed(2);
}
</script>
Upvotes: 0
Reputation: 68635
Wrap the prior operation with ()
. It first evaluates the function
call on the number, so first goes 0.0328084.toFixed(2)
then the result of this with valNum
.
(valNum*0.0328084).toFixed(2)
Example
function LengthConverter(valNum) {
document.getElementById("outputFeet").innerHTML = (valNum*0.0328084).toFixed(2);
}
<p>
<label>Centimeter</label>
<input id="inputCentimeter" type="number" placeholder="Centimeter"
oninput="LengthConverter(this.value)"
onchange="LengthConverter(this.value)">
</p>
<p>Feet: <span id="outputFeet"></span></p>
Upvotes: 2