fix(roundNumber): handle negative numbers properly (#4336)

This commit is contained in:
Ibrahim 2024-08-15 11:13:27 -04:00 committed by GitHub
parent a2be64f899
commit 7377db8d28
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -10,24 +10,33 @@
* @param value - to return a fixed measurement value from
* @param precision - defining how many digits after 1..9 are desired
*/
function roundNumber(value: string | number, precision = 2): string {
if (value === undefined || value === null || value === '') return 'NaN';
function roundNumber(value, precision = 2) {
if (Array.isArray(value)) {
return value.map((v) => roundNumber(v, precision)).join(", ");
}
if (value === undefined || value === null || value === "") {
return "NaN";
}
value = Number(value);
if (value < 0.0001) return `${value}`;
const absValue = Math.abs(value);
if (absValue < 0.0001) {
return `${value}`;
}
const fixedPrecision =
value >= 100
absValue >= 100
? precision - 2
: value >= 10
? precision - 1
: value >= 1
? precision
: value >= 0.1
? precision + 1
: value >= 0.01
? precision + 2
: value >= 0.001
? precision + 3
: precision + 4;
: absValue >= 10
? precision - 1
: absValue >= 1
? precision
: absValue >= 0.1
? precision + 1
: absValue >= 0.01
? precision + 2
: absValue >= 0.001
? precision + 3
: precision + 4;
return value.toFixed(fixedPrecision);
}