Skip to content

Commit 3499936

Browse files
authored
fix: negative values formatting (#1687)
Signed-off-by: Pedro Lamas <[email protected]>
1 parent d2335a9 commit 3499936

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/util/string-formatters.ts

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@ const stringFormatters = () => {
3636
return `0${unit}`
3737
}
3838

39-
return Math.max(value, Math.pow(10, -fractionDigits))
39+
const op = value < 0 ? Math.min : Math.max
40+
41+
return op(value, Math.pow(10, -fractionDigits))
4042
.toFixed(fractionDigits) + unit
4143
},
4244

@@ -85,19 +87,21 @@ const stringFormatters = () => {
8587
* Formats a number representing mm to human readable distance.
8688
*/
8789
getReadableLengthString: (lengthInMm: number, options?: { showMicrons?: boolean, showKilometers?: boolean }, fractionDigits: number | undefined = undefined) => {
88-
if (lengthInMm >= 1000000 && options?.showKilometers) {
90+
const absLengthInMm = Math.abs(lengthInMm)
91+
92+
if (absLengthInMm >= 1000000 && options?.showKilometers) {
8993
return (lengthInMm / 1000000).toFixed(fractionDigits ?? 2) + ' km'
9094
}
9195

92-
if (lengthInMm >= 1000) {
96+
if (absLengthInMm >= 1000) {
9397
return (lengthInMm / 1000).toFixed(fractionDigits ?? 2) + ' m'
9498
}
9599

96-
if (lengthInMm > 100) {
100+
if (absLengthInMm > 100) {
97101
return (lengthInMm / 10).toFixed(fractionDigits ?? 1) + ' cm'
98102
}
99103

100-
if (lengthInMm < 0.1 && options?.showMicrons) {
104+
if (absLengthInMm < 0.1 && options?.showMicrons) {
101105
return instance.getStringValueWithUnit(lengthInMm * 1000, fractionDigits ?? 0, ' μm')
102106
}
103107

@@ -108,7 +112,9 @@ const stringFormatters = () => {
108112
* Formats a number representing g to human readable weight.
109113
*/
110114
getReadableWeightString: (weightInG: number, fractionDigits = 2) => {
111-
if (weightInG >= 1000) {
115+
const absWeightInG = Math.abs(weightInG)
116+
117+
if (absWeightInG >= 1000) {
112118
return (weightInG / 1000).toFixed(fractionDigits) + ' kg'
113119
}
114120

@@ -120,7 +126,7 @@ const stringFormatters = () => {
120126
*/
121127
getReadableFrequencyString: (frequencyInHz: number, fractionDigits = 0) => {
122128
let i = 0
123-
while (frequencyInHz >= 1000) {
129+
while (Math.abs(frequencyInHz) >= 1000) {
124130
frequencyInHz = frequencyInHz / 1000
125131
i++
126132
}
@@ -133,7 +139,7 @@ const stringFormatters = () => {
133139
*/
134140
getReadableResistanceString: (resistanceInOhms: number, fractionDigits = 1) => {
135141
let i = 0
136-
while (resistanceInOhms >= 1000) {
142+
while (Math.abs(resistanceInOhms) >= 1000) {
137143
resistanceInOhms = resistanceInOhms / 1000
138144
i++
139145
}

0 commit comments

Comments
 (0)