From ad2c99ba0c1e6772860226c4459849f9f1dcfdc4 Mon Sep 17 00:00:00 2001 From: Joris Date: Mon, 3 May 2021 21:15:54 +0200 Subject: Fix number inputs --- public/main.js | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) (limited to 'public') diff --git a/public/main.js b/public/main.js index 68deeee..24d2f8d 100644 --- a/public/main.js +++ b/public/main.js @@ -6,7 +6,7 @@ window.onload = function() { document.querySelectorAll('.number').forEach(function (number) { // Install input - const value = parseInt(number.innerHTML) + const value = parseFloat(number.innerHTML) number.innerHTML = `` // Push to inputs @@ -28,7 +28,7 @@ window.onload = function() { // Apply factor to other inputs inputs.forEach(function (input) { if (input.element !== currentInput.element) { - input.element.value = formatNumber(factor * input.value) + input.element.value = formatNumber(factor, input.value) } }) } @@ -45,11 +45,24 @@ window.onload = function() { } -function formatNumber(n) { - const xs = n.toString().split('.') - if (xs.length == 2) { - return `${xs[0]}.${xs[1].slice(0, 1)}` +function formatNumber(factor, value) { + if (factor === 1) { + return value } else { - return n + const n = factor * value + const xs = n.toString().split('.') + const p = precision(value) || 1 + if (xs.length == 2) { + return `${xs[0]}.${xs[1].slice(0, p)}` + } else { + return n + } + } +} + +function precision(value) { + const xs = value.toString().split('.') + if (xs.length === 2) { + return xs[1].length } } -- cgit v1.2.3