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
This commit is contained in:
mfish33 2022-01-06 18:45:37 -08:00 committed by Keavon Chambers
parent c98bee6470
commit 52e5501d18
1 changed files with 16 additions and 10 deletions

View File

@ -152,6 +152,8 @@
<script lang="ts">
import { defineComponent, PropType } from "vue";
import { clamp } from "@/utilities/math";
export type IncrementBehavior = "Add" | "Multiply" | "Callback" | "None";
export type IncrementDirection = "Decrease" | "Increase";
@ -240,13 +242,21 @@ export default defineComponent({
if (invalid) sanitized = this.value;
if (this.isInteger) sanitized = Math.round(sanitized);
if (typeof this.min === "number" && !Number.isNaN(this.min)) sanitized = Math.max(sanitized, this.min);
if (typeof this.max === "number" && !Number.isNaN(this.max)) sanitized = Math.min(sanitized, this.max);
sanitized = clamp(newValue, this.min, this.max);
if (!invalid) this.$emit("update:value", sanitized);
const roundingPower = 10 ** this.displayDecimalPlaces;
const displayValue = Math.round(sanitized * roundingPower) / roundingPower;
this.setText(sanitized);
},
setText(value: number) {
// Find the amount of digits on the left side of the Decimal
// 10.25 == 2
// 1.23 == 1
// 0.23 == 0 - Reason for the slightly more complicated code
const leftSideDigits = Math.max(Math.floor(value).toString().length, 0) * Math.sign(value);
const roundingPower = 10 ** Math.max(this.displayDecimalPlaces - leftSideDigits, 0);
const displayValue = Math.round(value * roundingPower) / roundingPower;
this.text = `${displayValue}${this.unit}`;
},
},
@ -258,13 +268,9 @@ export default defineComponent({
return;
}
let sanitized = newValue;
if (typeof this.min === "number") sanitized = Math.max(sanitized, this.min);
if (typeof this.max === "number") sanitized = Math.min(sanitized, this.max);
const sanitized = clamp(newValue, this.min, this.max);
const roundingPower = 10 ** this.displayDecimalPlaces;
const displayValue = Math.round(sanitized * roundingPower) / roundingPower;
this.text = `${displayValue}${this.unit}`;
this.setText(sanitized);
},
},
mounted() {