I am trying to have a user input their number into an HTML input tag, and then have them click a button and output a fixed number with two decimal points. I am unable to get it to work even though I have followed examples and even copied what they did at points, not sure what I am doing wrong. I am pretty new to JavaScript so I don't quite understand what I am doing.
HTML:
<p> Input below to fix your number </p>
<input id="input1" type="number" placeholder="number 1">
<button onclick="javascript:tofixed_method()">CLICK</button>
<p> Your fixed number: <span id="answer"></span></p>
JavaScript:
function tofixed_method() {
var val1 = document.getElementById("input1").value;
var val2 = val1.toFixed(2);
document.getElementById("answer").innerHTML = val2;
}
Thank you!
CodePudding user response:
document.getElementById("input1").value
gives you a string. You need to turn it into a number first, using parseInt
for example:
function tofixed_method() {
var val1 = document.getElementById("input1").value;
var val2 = parseInt(val1).toFixed(2);
document.getElementById("answer").innerHTML = val2;
}
CodePudding user response:
You can refer to the logic of rc-input-number.There are many factors to consider.
// '1.' '1x' 'xx' '' => are not complete numbers
function isNotCompleteNumber(num) {
return (
isNaN(num) ||
num === '' ||
num === null ||
(num && num.toString().indexOf('.') === num.toString().length - 1)
);
}
function tofixed_method() {
const input_value = document.getElementById('input1').value;
const input_num = parseFloat(input_value, 10);
document.getElementById('answer').innerHTML = isNotCompleteNumber(input_num) ? '' : input_num.toFixed(2);
}