如何使 HTML5 数字字段显示尾随零?
我有一个字段:
<input type='number' />
我想输入 0.50
而不将其“更正”为 0.5
,因此它会显示 0.50
。
I have a field:
<input type='number' />
I'd like to punch in 0.50
without it “correcting it” to 0.5
, so it would display 0.50
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将 on('change') 事件附加到您想要尾随 0 的输入,
它只需获取该值,将其转换为浮点数,将其呈现为小数位数的字符串,然后将其放回价值。
I attached an on('change') event to the input you want to have trailing 0's
It just takes the value, casts it to a float, renders it to a string to the number of decimal places, and puts it back in as the value.
我对此进行了一些尝试并查看了规范。它说它必须是一个有效的浮点数。 有效浮点的定义中有一句话它给出的数字引起了我的注意:
这意味着格式将始终与评估数字是什么,然后对该数字使用 JavaScript 的 toString 保持一致。所以没有尾随 0。
因此,您将不得不求助于 JavaScript。这并不简单,因为
document.getElementById('numInput').value = '0.50';
仍会更正为0.5
,因此验证不会在 < code>onchange 可以阻止默认操作,它是在内部触发的。这是我能想到的最好的解决方案......这有点麻烦,并且需要进行一些调整以提高鲁棒性,但希望它能达到您想要的效果:
因此,如果用户想通过以下方式输入数字键入时,它将输入类型切换为文本,但是当他们单击它时,它将其转换回数字。
如果无论用户输入什么,您总是想要尾随 0,那么您可以这样做:
编辑: 我认为第二个解决方案更符合用户可能的期望,但这意味着如果用户输入
0.5
,它将被强制为0.50
,所以这取决于这是否是您想要的。I've had a little play around with this and looked at the spec. It says that it must be a valid floating point number. There's one sentence in the definition of a valid floating point number it gives which caught my attention:
This means that the format will always be consistent with assessing what the number is, then using JavaScript's toString on that number. So no trailing 0s then.
So, you're going to have to resort to JavaScript. This isn't straightforward because
document.getElementById('numInput').value = '0.50';
still gets corrected to0.5
, so the validation isn't triggered atonchange
where the default action can be prevented, it's triggered internally.This is the best solution I could come up with... it's a bit of a hack, and will need a bit of tweaking for robustness, but hopefully it'll do what you want:
So if the user wants to enter the number by typing, it switches the input type to text, but when they click it, it converts it back to a number.
If you always want the trailing 0s no matter what the user types, then you could do it something like this:
Edit: I think the second solution is more inline with what the user might expect, but it means that if the user types
0.5
it will be coerced to0.50
, so it depends if that's what you want.