当前位置: 代码迷 >> 综合 >> jquery将input type=number 值保留两位小数(四舍五入)
  详细解决方案

jquery将input type=number 值保留两位小数(四舍五入)

热度:34   发布时间:2023-11-04 22:17:00.0

背景: 

    from表单填写商品价格时,需要写成两位小数类型,如 2.00 元;

实现:

   //form表单

 <div class="form-line"><lable><i>*</i>价格:</lable><input type="number" class="number" name="price" min="0.01" step="0.01"><div class="error-msg"></div></div>

//jquery

    $(".number").change(function () {var val = $(this).val();$(this).val(toDecimal2(val));});function toDecimal2(x) {var f = parseFloat(x);if (isNaN(f)) {return false;}var f = Math.round(x*100)/100;var s = f.toString();var rs = s.indexOf('.');if (rs < 0) {rs = s.length;s += '.';}while (s.length <= rs + 2) {s += '0';}return s;}

即可实现;

扩展:

   实现保留一位小数,可根据以上代码做微调整;

实现:

  //form表单

<div class="form-line"><lable><i>*</i>版本:</lable><input type="number" class="version" name="version" min="0.1" step="0.1"><div class="error-msg"></div>
</div>

//jquery

 $(".version").change(function () {var val = $(this).val();$(this).val(toDecimal1(val));});function toDecimal1(x) {var f = parseFloat(x);if (isNaN(f)) {return false;}var f = Math.round(x*10)/10;var s = f.toString();var rs = s.indexOf('.');if (rs < 0) {rs = s.length;s += '.';}while (s.length <= rs + 1) {s += '0';}return s;}

完成。

  相关解决方案