el-input-number设置step、stepStrictly后,数据精度丢失的问题

el-input-number的配置

<el-input-number
  v-else-if="colInputType(column, row) === 'number'"
  v-model="row[column.key]"
  :placeholder="`${$t('documentation.pleaseInput')}`"
  :controls="false"
  :min="minFn(column, row)"
  :max="maxFn(column, row)"
  :step-strictly="true"
  :step="0.00001"
  :disabled="itemDisabled(column, row)"
  clearable
  @change="
    (value) =>
      inputNumberEditorOnChange(value, $index, column, row)
  "
  v-bind="column"
>
el-input-number>```

这里是设置5位小数的step,初始化时,用户修改时,很容易有精度问题;
设置4位小数step,需要在特定数字时,才能回体现这个bug;
el-input-number设置step、stepStrictly后,数据精度丢失的问题_第1张图片
根本原因:

element底层组件el-input-number的监听函数有问题;
el-input-number设置step、stepStrictly后,数据精度丢失的问题_第2张图片
测试代码如下

function getPrecision(value) {
  if (value === undefined) return 0;
  const valueString = value.toString();
  const dotPosition = valueString.indexOf('.');
  let precision = 0;
  if (dotPosition !== -1) {
    precision = valueString.length - dotPosition - 1;
  }
  return precision;
}
function test(value, step) {
  let newVal = value === undefined ? value : Number(value);
  if (newVal !== undefined) {
    if (isNaN(newVal)) {
      return;
    }

    if (true) {
      const stepPrecision = getPrecision(step);
      const precisionFactor = Math.pow(10, stepPrecision);
      newVal = Math.round(newVal / step) * precisionFactor * step / precisionFactor;
    }

    return newVal;
  }
}
test(1088, 0.00001); //* 1088.0000000000002

解决方案:
1、stepPrecision为false,封装个组件,手动进行圆整;
2、stepPrecision为true,结合precision一起使用;

你可能感兴趣的:(vue.js,前端)