[英]User input and toFixed method not working
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.我试图让用户将他们的数字输入到 HTML 输入标签中,然后让他们单击一个按钮并输出一个带有两个小数点的固定数字。 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.
我对 JavaScript 很陌生,所以我不太明白我在做什么。
HTML: 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: JavaScript:
function tofixed_method() {
var val1 = document.getElementById("input1").value;
var val2 = val1.toFixed(2);
document.getElementById("answer").innerHTML = val2;
} }
Thank you!谢谢!
document.getElementById("input1").value
gives you a string. document.getElementById("input1").value
给你一个字符串。 You need to turn it into a number first, using parseInt
for example:您需要先将其转换为数字,例如使用
parseInt
:
function tofixed_method() {
var val1 = document.getElementById("input1").value;
var val2 = parseInt(val1).toFixed(2);
document.getElementById("answer").innerHTML = val2;
}
You can refer to the logic of rc-input-number.There are many factors to consider.可以参考rc-input-number的逻辑,要考虑的因素很多。
// '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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.