diff --git a/packages/flint-js/src/core/field-semantics.ts b/packages/flint-js/src/core/field-semantics.ts index edb1c082..08d074d0 100644 --- a/packages/flint-js/src/core/field-semantics.ts +++ b/packages/flint-js/src/core/field-semantics.ts @@ -58,6 +58,9 @@ export interface SemanticAnnotation { */ intrinsicDomain?: [number, number]; + /** How percentage values are stored: fractions (0.45) or percent points (45). */ + percentScale?: 'fraction' | 'percent'; + /** Unit or currency code. E.g., "USD", "°C", "kg" */ unit?: string; @@ -422,7 +425,11 @@ export function resolveFormat( if (!annotation.intrinsicDomain) { return { tooltipFormat: { pattern: precisionFormat(nums) } }; } - const rep = detectPercentageRepresentation(nums); + const rep = annotation.percentScale === 'fraction' + ? '0-1' + : annotation.percentScale === 'percent' + ? '0-100' + : detectPercentageRepresentation(nums); if (rep === '0-1') { // 0–1 fractional → axis must transform (0.45 → "45%") const p = detectPrecision(nums); diff --git a/packages/flint-js/tests/percentage-format.test.ts b/packages/flint-js/tests/percentage-format.test.ts new file mode 100644 index 00000000..5ee0c686 --- /dev/null +++ b/packages/flint-js/tests/percentage-format.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest'; +import { resolveFormat } from '../src/core/field-semantics'; + +describe('percentage representation annotations', () => { + const values = [0.5, 1.8, 2.4, 3, 1.2]; + + it('uses an explicit fractional scale even when most values exceed one', () => { + expect(resolveFormat('PercentageChange', { + semanticType: 'PercentageChange', + intrinsicDomain: [0, 3], + percentScale: 'fraction', + }, values)).toEqual({ + format: { pattern: '.0~%' }, + tooltipFormat: { pattern: '.1%' }, + }); + }); + + it('uses an explicit percent-point scale even when most values are at most one', () => { + expect(resolveFormat('Percentage', { + semanticType: 'Percentage', + intrinsicDomain: [0, 100], + percentScale: 'percent', + }, [0.2, 0.4, 0.5, 0.8, 3])).toEqual({ + tooltipFormat: { pattern: '.1f', suffix: '%' }, + }); + }); + + it('keeps data-driven detection when no explicit scale is supplied', () => { + expect(resolveFormat('PercentageChange', { + semanticType: 'PercentageChange', + intrinsicDomain: [0, 3], + }, values)).toEqual({ + tooltipFormat: { pattern: '.1f', suffix: '%' }, + }); + }); +});