uniapp input @input 控制显示小数点后两位不生效怎么办?
在uniapp中使用input组件的@input事件限制用户只能输入小数点后两位时,发现无法生效。例如输入123.456时,期望自动截断为123.45,但实际仍显示完整输入值。尝试过通过正则表达式或toFixed(2)处理数据,但要么无法实时更新,要么导致输入框闪烁。请问如何正确实现这一功能?需兼容H5和小程序平台。
2 回复
在@input事件里用正则处理:value.replace(/\.\d{2}\d*/g, '$1$2$3'),或者用parseFloat(value).toFixed(2),注意处理非数字情况。
在uni-app中,使用@input事件控制输入框只显示小数点后两位时,如果发现不生效,通常是因为输入事件触发时值已经包含多余小数位。以下是解决方案:
1. 使用正则表达式过滤输入
在@input事件中,通过正则表达式实时过滤输入值,保留最多两位小数。
<template>
<input
type="digit"
v-model="inputValue"
@input="handleInput"
placeholder="请输入数字"
/>
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
methods: {
handleInput(e) {
let value = e.detail.value;
// 正则匹配:允许数字和小数点,且小数点后最多两位
value = value.replace(/[^\d.]/g, '').replace(/(\.\d{2})\d+/, '$1');
this.inputValue = value;
}
}
}
</script>
2. 使用onBlur事件处理(推荐)
在输入框失去焦点时格式化数值,避免输入过程中频繁干扰。
<template>
<input
type="digit"
v-model="inputValue"
@blur="formatDecimal"
placeholder="请输入数字"
/>
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
methods: {
formatDecimal() {
if (this.inputValue) {
// 转换为数字并固定两位小数
this.inputValue = parseFloat(this.inputValue).toFixed(2);
}
}
}
}
</script>
注意事项:
- 使用
type="digit"限制输入类型为数字(带小数点)。 - 正则方法在输入过程中实时过滤,但可能影响用户体验。
onBlur方法在输入完成后格式化,更友好。- 若数值可能为空,需添加空值判断避免
NaN错误。
选择其中一种方法即可解决问题。

