diff --git a/test/ui/number-input-precision.spec.js b/test/ui/number-input-precision.spec.js new file mode 100644 index 000000000..dc3276964 --- /dev/null +++ b/test/ui/number-input-precision.spec.js @@ -0,0 +1,26 @@ +const should = require('should') // eslint-disable-line no-unused-vars + +const { stepPrecision } = require('../../ui/src/widgets/ui-number-input/precision.js') + +describe('ui-number-input precision', function () { + const cases = [ + [1e-7, 7], + [-1.25e-7, 9], + [0.25, 2], + [1, 0], + [0, 0], + [1e21, 0], + [1e-100, 100] + ] + + for (const [step, expected] of cases) { + it(`uses ${expected} decimal places for ${step}`, function () { + stepPrecision(step).should.equal(expected) + }) + } + + it('preserves a small step when formatted with toFixed', function () { + const step = 1e-7 + step.toFixed(stepPrecision(step)).should.equal('0.0000001') + }) +}) diff --git a/ui/src/widgets/ui-number-input/UINumberInput.vue b/ui/src/widgets/ui-number-input/UINumberInput.vue index d03a09ca3..51ce8666d 100644 --- a/ui/src/widgets/ui-number-input/UINumberInput.vue +++ b/ui/src/widgets/ui-number-input/UINumberInput.vue @@ -26,6 +26,8 @@ import DOMPurify from 'dompurify' import { VNumberInput } from 'vuetify/lib/components/VNumberInput/VNumberInput' import { mapState } from 'vuex' // eslint-disable-line import/order +import { stepPrecision } from './precision.js' + export default { name: 'DBUITextInput', components: { @@ -103,8 +105,7 @@ export default { return Math.abs(this.getProperty('step')) || 1 }, precision () { - const s = Math.abs(this.getProperty('step')) || 1 - return s.toString().split('.')[1]?.length || 0 + return stepPrecision(this.step) }, spinner () { return this.getProperty('spinner') diff --git a/ui/src/widgets/ui-number-input/precision.js b/ui/src/widgets/ui-number-input/precision.js new file mode 100644 index 000000000..d782aa311 --- /dev/null +++ b/ui/src/widgets/ui-number-input/precision.js @@ -0,0 +1,13 @@ +function stepPrecision (step) { + const [coefficient, exponent = '0'] = step.toString().split('e') + const fractionDigits = coefficient.split('.')[1]?.length || 0 + // VNumberInput uses toFixed(), which accepts at most 100 digits. + return Math.min(100, Math.max(0, fractionDigits - Number(exponent))) +} + +export { stepPrecision } + +if (typeof module !== 'undefined' && module.exports) { + module.exports = { stepPrecision } + module.exports.default = module.exports +}