Skip to content

Commit 8b3edb0

Browse files
mfish33Keavon
authored andcommitted
Better decimal rounding in the NumberInput widget (#457)
* better decimal rounding in NumberInput * - created function to reuse - used math instead of string manipulation * updated comment to be correct * updated comment * updated comment
1 parent c9848a1 commit 8b3edb0

File tree

1 file changed

+16
-10
lines changed

1 file changed

+16
-10
lines changed

frontend/src/components/widgets/inputs/NumberInput.vue

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,8 @@
152152
<script lang="ts">
153153
import { defineComponent, PropType } from "vue";
154154
155+
import { clamp } from "@/utilities/math";
156+
155157
export type IncrementBehavior = "Add" | "Multiply" | "Callback" | "None";
156158
export type IncrementDirection = "Decrease" | "Increase";
157159
@@ -240,13 +242,21 @@ export default defineComponent({
240242
if (invalid) sanitized = this.value;
241243
242244
if (this.isInteger) sanitized = Math.round(sanitized);
243-
if (typeof this.min === "number" && !Number.isNaN(this.min)) sanitized = Math.max(sanitized, this.min);
244-
if (typeof this.max === "number" && !Number.isNaN(this.max)) sanitized = Math.min(sanitized, this.max);
245+
sanitized = clamp(newValue, this.min, this.max);
245246
246247
if (!invalid) this.$emit("update:value", sanitized);
247248
248-
const roundingPower = 10 ** this.displayDecimalPlaces;
249-
const displayValue = Math.round(sanitized * roundingPower) / roundingPower;
249+
this.setText(sanitized);
250+
},
251+
setText(value: number) {
252+
// Find the amount of digits on the left side of the Decimal
253+
// 10.25 == 2
254+
// 1.23 == 1
255+
// 0.23 == 0 - Reason for the slightly more complicated code
256+
const leftSideDigits = Math.max(Math.floor(value).toString().length, 0) * Math.sign(value);
257+
258+
const roundingPower = 10 ** Math.max(this.displayDecimalPlaces - leftSideDigits, 0);
259+
const displayValue = Math.round(value * roundingPower) / roundingPower;
250260
this.text = `${displayValue}${this.unit}`;
251261
},
252262
},
@@ -258,13 +268,9 @@ export default defineComponent({
258268
return;
259269
}
260270
261-
let sanitized = newValue;
262-
if (typeof this.min === "number") sanitized = Math.max(sanitized, this.min);
263-
if (typeof this.max === "number") sanitized = Math.min(sanitized, this.max);
271+
const sanitized = clamp(newValue, this.min, this.max);
264272
265-
const roundingPower = 10 ** this.displayDecimalPlaces;
266-
const displayValue = Math.round(sanitized * roundingPower) / roundingPower;
267-
this.text = `${displayValue}${this.unit}`;
273+
this.setText(sanitized);
268274
},
269275
},
270276
mounted() {

0 commit comments

Comments
 (0)