Skip to content

Commit 96da9a3

Browse files
committed
fix: #3614 avoid unnecessary parentheses for complex values of a unit
1 parent 83ce3cb commit 96da9a3

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/type/unit/Unit.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { isComplex, isUnit, typeOf } from '../../utils/is.js'
22
import { factory } from '../../utils/factory.js'
33
import { memoize } from '../../utils/function.js'
4+
import { nearlyEqual } from '../../utils/number.js'
45
import { endsWith } from '../../utils/string.js'
56
import { clone, hasOwnProperty } from '../../utils/object.js'
67
import { createBigNumberPi as createPi } from '../../utils/bignumber/constants.js'
@@ -1175,7 +1176,12 @@ export const createUnitClass = /* #__PURE__ */ factory(name, dependencies, ({
11751176
Unit.prototype.format = function (options) {
11761177
const { simp, valueStr, unitStr } = formatBest(this, options)
11771178
let str = valueStr
1178-
if (simp.value && isComplex(simp.value)) {
1179+
if (
1180+
simp.value &&
1181+
isComplex(simp.value) &&
1182+
!nearlyEqual(simp.value.re, 0) &&
1183+
!nearlyEqual(simp.value.im, 0)
1184+
) {
11791185
str = '(' + str + ')' // Surround complex values with ( ) to enable better parsing
11801186
}
11811187
if (unitStr.length > 0 && str.length > 0) {

test/unit-tests/type/unit/Unit.test.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -771,14 +771,17 @@ describe('Unit', function () {
771771

772772
it('should format a Complex unit', function () {
773773
assert.strictEqual(new Unit(math.complex(-2, 4.5), 'mm').format(14), '(-2 + 4.5i) mm')
774+
assert.strictEqual(new Unit(math.complex(1), 'kW').format(14), '1 kW')
775+
assert.strictEqual(new Unit(math.complex(0, 1), 'kW').format(14), 'i kW')
776+
assert.strictEqual(new Unit(math.complex(0, 2), 'kW').format(14), '2i kW')
774777
})
775778

776779
it('should format units with VA and VAR correctly', function () {
777780
assert.strictEqual(math.evaluate('4000 VAR + 3000 VA').format(), '(3 + 4i) kVA')
778781
assert.strictEqual(math.evaluate('3000 VA + 4000 VAR').format(), '(3 + 4i) kVA')
779-
assert.strictEqual(math.evaluate('4000 VAR').format(), '(4) kVAR')
780-
assert.strictEqual(math.evaluate('4000i VA').format(), '(4) kVAR')
781-
assert.strictEqual(math.evaluate('4000i VAR').format(), '(-4) kVA')
782+
assert.strictEqual(math.evaluate('4000 VAR').format(), '4 kVAR')
783+
assert.strictEqual(math.evaluate('4000i VA').format(), '4 kVAR')
784+
assert.strictEqual(math.evaluate('4000i VAR').format(), '-4 kVA')
782785
assert.strictEqual(math.evaluate('abs(4000 VAR + 3000 VA)').format(), '5 kW')
783786
assert.strictEqual(math.evaluate('abs(3000 VA + 4000 VAR)').format(), '5 kW')
784787
assert.strictEqual(math.evaluate('abs(4000 VAR)').format(), '4 kW')

0 commit comments

Comments
 (0)