Skip to content

Commit

Permalink
Scientific notation formatting
Browse files Browse the repository at this point in the history
Co-authored-by: Phil DeOrsey <pdeorsey@amplify.com>
  • Loading branch information
plegner and PhilDeOrsey committed Aug 20, 2023
1 parent 7bcc793 commit e107de8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
16 changes: 16 additions & 0 deletions src/arithmetic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,22 @@ export function numberFormat(n: number, places = 0, separators = true) {
return separators ? addThousandSeparators(str) : str;
}

export function scientificFormat(value: number, places = 6) {
const abs = Math.abs(value);
if (isBetween(abs, Math.pow(10, -places), Math.pow(10, places))) {
return numberFormat(value, places);
}

// TODO Decide how we want to handle these special cases
if (abs > Number.MAX_VALUE) return `${Math.sign(value) < 0 ? '–' : ''}∞`;
if (abs < Number.MIN_VALUE) return '0';

const [str, exponent] = value.toExponential().split('e');
const top = exponent.replace('+', '').replace('-', '–');
const isNegative = top.startsWith('–');
return `${str.slice(0, 5)} × 10^${(isNegative ? '(' : '') + top + (isNegative ? ')' : '')}`;
}

// Numbers like 0,123 are decimals, even though they match POINT_DECIMAL.
const SPECIAL_DECIMAL = /^-?0,[0-9]+$/;

Expand Down
14 changes: 13 additions & 1 deletion test/arithmetic-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


import tape from 'tape';
import {numberFormat, parseNumber, toWord} from '../src';
import {numberFormat, parseNumber, scientificFormat, toWord} from '../src';


tape('numberFormat', (test) => {
Expand Down Expand Up @@ -43,6 +43,18 @@ tape('numberFormat', (test) => {
test.equal(numberFormat(0.001, 3), '0', ':: numberFormat(0.001, 3)');
test.equal(numberFormat(-0.001, 5), '–0.001', ':: numberFormat(-0.001, 5)');
test.equal(numberFormat(-0.001, 4), '0', ':: numberFormat(-0.001, 4)');

test.equal(scientificFormat(123123123, 6), '1.231 × 10^8');
test.equal(scientificFormat(123123, 6), '123,123');
test.equal(scientificFormat(-123123123, 6), '-1.23 × 10^8');

test.equal(scientificFormat(0.000123, 6), '0.00012');
test.equal(scientificFormat(0.000000123, 6), '1.23 × 10^(–7)');
test.equal(scientificFormat(-0.000000123, 6), '-1.23 × 10^(–7)');

test.equal(scientificFormat(-Number.MAX_VALUE * 10, 6), '–∞');
test.equal(scientificFormat(-Number.MIN_VALUE / 10, 6), '0');

test.end();
});

Expand Down

0 comments on commit e107de8

Please sign in to comment.