From 96da9a3506b0d73a4890d830c9b8cfa6117cf3cf Mon Sep 17 00:00:00 2001 From: Jos de Jong Date: Wed, 7 Jan 2026 17:15:46 +0100 Subject: [PATCH] fix: #3614 avoid unnecessary parentheses for complex values of a unit --- src/type/unit/Unit.js | 8 +++++++- test/unit-tests/type/unit/Unit.test.js | 9 ++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/type/unit/Unit.js b/src/type/unit/Unit.js index daebd92a87..bb1f1e5ad5 100644 --- a/src/type/unit/Unit.js +++ b/src/type/unit/Unit.js @@ -1,6 +1,7 @@ import { isComplex, isUnit, typeOf } from '../../utils/is.js' import { factory } from '../../utils/factory.js' import { memoize } from '../../utils/function.js' +import { nearlyEqual } from '../../utils/number.js' import { endsWith } from '../../utils/string.js' import { clone, hasOwnProperty } from '../../utils/object.js' import { createBigNumberPi as createPi } from '../../utils/bignumber/constants.js' @@ -1175,7 +1176,12 @@ export const createUnitClass = /* #__PURE__ */ factory(name, dependencies, ({ Unit.prototype.format = function (options) { const { simp, valueStr, unitStr } = formatBest(this, options) let str = valueStr - if (simp.value && isComplex(simp.value)) { + if ( + simp.value && + isComplex(simp.value) && + !nearlyEqual(simp.value.re, 0) && + !nearlyEqual(simp.value.im, 0) + ) { str = '(' + str + ')' // Surround complex values with ( ) to enable better parsing } if (unitStr.length > 0 && str.length > 0) { diff --git a/test/unit-tests/type/unit/Unit.test.js b/test/unit-tests/type/unit/Unit.test.js index 2803daf984..4da0c8c996 100644 --- a/test/unit-tests/type/unit/Unit.test.js +++ b/test/unit-tests/type/unit/Unit.test.js @@ -771,14 +771,17 @@ describe('Unit', function () { it('should format a Complex unit', function () { assert.strictEqual(new Unit(math.complex(-2, 4.5), 'mm').format(14), '(-2 + 4.5i) mm') + assert.strictEqual(new Unit(math.complex(1), 'kW').format(14), '1 kW') + assert.strictEqual(new Unit(math.complex(0, 1), 'kW').format(14), 'i kW') + assert.strictEqual(new Unit(math.complex(0, 2), 'kW').format(14), '2i kW') }) it('should format units with VA and VAR correctly', function () { assert.strictEqual(math.evaluate('4000 VAR + 3000 VA').format(), '(3 + 4i) kVA') assert.strictEqual(math.evaluate('3000 VA + 4000 VAR').format(), '(3 + 4i) kVA') - assert.strictEqual(math.evaluate('4000 VAR').format(), '(4) kVAR') - assert.strictEqual(math.evaluate('4000i VA').format(), '(4) kVAR') - assert.strictEqual(math.evaluate('4000i VAR').format(), '(-4) kVA') + assert.strictEqual(math.evaluate('4000 VAR').format(), '4 kVAR') + assert.strictEqual(math.evaluate('4000i VA').format(), '4 kVAR') + assert.strictEqual(math.evaluate('4000i VAR').format(), '-4 kVA') assert.strictEqual(math.evaluate('abs(4000 VAR + 3000 VA)').format(), '5 kW') assert.strictEqual(math.evaluate('abs(3000 VA + 4000 VAR)').format(), '5 kW') assert.strictEqual(math.evaluate('abs(4000 VAR)').format(), '4 kW')