uniapp小程序,输入框限制输入(正整数、小数后几位)

html 复制代码
  <uv-input inputAlign="right" type="number" v-model="quantity" placeholder="请输入单价"
    border="none" @input="e => handleInput(e, 2)"/>
javascript 复制代码
const quantity = ref()
const handleInput = (e, decimals) =>{
  //setTimeout解决input不及时更新
  setTimeout(() => {
    quantity = handleNumberInput(e, decimals)
  }, 0)
}
/**
 * 处理数字输入
 */
 function handleNumberInput (
  e: string | number /**输入的值 */,
  decimals: number = 2 /**小数点位数 */
) => {
  if (e === "") return;
  let result = "";
  result = String(e);
  // 只能输入正整数
  if (!decimals) {
    return (
      result
        // 第一步:去除非数字和小数点
        .replace(/[^\d.]/g, "")
        // 第二步:替换开头的0、所有非数字字符、所有小数点
        .replace(/^0|[^\d]|[.]/g, "")
    );
  }
  // 处理小数位数
  if (decimals > 0) {
    const decimalRegex = new RegExp(`(\\.\\d{${decimals}})\\d+$`, "g");
    result = result
      // 第一步:去除非数字和小数点
      .replace(/[^\d.]/g, "")
      // 第二步:处理前导0(非零开头的数字)
      .replace(/^0+(\d)/, "$1")
      // 第三步:处理开头单独的小数点,转为0.
      .replace(/^\./, "0.")
      // 第四步:保留第一个小数点,去掉多余的
      .replace(/\./g, (s, offset, str) =>
        offset === str.indexOf(".") ? s : ""
      )
      // 第五步:截断小数部分到decimals位
      .replace(decimalRegex, "$1")
      // 第六步:处理整数部分的前导0(比如0后面没有小数点的情况)
      .replace(/^0+([1-9])/, "$1")
      // 确保精确到指定位数
      .replace(new RegExp(`(\\.[\\d]{${decimals}}).*$`), "$1"); 
  }
  return result;
};
相关推荐
游戏开发爱好者82 小时前
日常开发与测试的 App 测试方法、查看设备状态、实时日志、应用数据
android·ios·小程序·https·uni-app·iphone·webview
2501_915106324 小时前
app 上架过程,安装包准备、证书与描述文件管理、安装测试、上传
android·ios·小程序·https·uni-app·iphone·webview
2501_915106324 小时前
使用 Sniffmaster TCP 抓包和 Wireshark 网络分析
网络协议·tcp/ip·ios·小程序·uni-app·wireshark·iphone
宠友信息6 小时前
2025社交+IM及时通讯社区APP仿小红书小程序
java·spring boot·小程序·uni-app·web app
“负拾捌”6 小时前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别
局外人LZ1 天前
Uniapp脚手架项目搭建,uniapp+vue3+uView pro+vite+pinia+sass
前端·uni-app·sass
光影少年1 天前
AIGC + Taro / 小程序
小程序·aigc·taro
2501_915918411 天前
在 iOS 环境下查看 App 详细信息与文件目录
android·ios·小程序·https·uni-app·iphone·webview
前端呆头鹅1 天前
Websocket使用方案详解(uniapp版)
websocket·网络协议·uni-app
浮桥1 天前
uniapp+h5 公众号实现分享海报绘制
uni-app·notepad++