Skip to content

Commit

Permalink
fix 0 precision commaNumber formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
KetanReddy committed Mar 8, 2024
1 parent 1c572a8 commit 2efc708
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ describe('commaNumber', () => {
expect(commaNumber.format?.(1000.999, { precision: 2 })).toBe('1,000.99');
expect(commaNumber.format?.(1000, { precision: 2 })).toBe('1,000.00');
expect(commaNumber.format?.(1000.1, { precision: 2 })).toBe('1,000.10');
expect(commaNumber.format?.(123456789, { precision: 0 })).toBe(
'123,456,789'
);
});

it('handles out of bounds', () => {
Expand Down
29 changes: 24 additions & 5 deletions plugins/common-types/core/src/formats/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ export const commaNumber: FormatType<
{
/** The number of decimal places to show */
precision?: number;
/** show zero in preDecDigits if true, hide otherwise */
showZero?: boolean;
/** show zero(es) in postDecDeigits if true, hide otherwise */
showZeroDecimal?: boolean;
}
> = {
name: 'commaNumber',
Expand All @@ -81,6 +85,8 @@ export const commaNumber: FormatType<
}

const value = String(_value);
const showZero = (options?.showZero as boolean) ?? true;
const showZeroDecimal = (options?.showZeroDecimal as boolean) ?? true;

// Check to see if first valid char is a negative
const isNeg = value.replace(/[^0-9.-]/g, '').charAt(0) === '-';
Expand Down Expand Up @@ -108,26 +114,39 @@ export const commaNumber: FormatType<
}

if (options?.precision !== undefined) {
postDecDigits = postDecDigits
.substring(0, options.precision)
.padEnd(options.precision, '0');
if (showZeroDecimal) {
postDecDigits = postDecDigits
.substring(0, options.precision)
.padEnd(options.precision, '0');
} else if (postDecDigits.length >= options.precision) {
postDecDigits =
Number(postDecDigits.substring(0, options.precision)) === 0
? ''
: postDecDigits.substring(0, options.precision);
}
}

// Beautify
preDecDigits = preDecDigits.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

if (preDecDigits === '' && firstDecimal === 0) {
preDecDigits = '0';
}

if (Number(preDecDigits) === 0 && !showZero && postDecDigits === '') {
preDecDigits = '';
}

// Put pieces together
let retVal = preDecDigits;

if (isNeg) {
retVal = `-${retVal}`;
}

if (firstDecimal >= 0 || options?.precision !== undefined) {
if (
(firstDecimal >= 0 || options?.precision !== undefined) &&
postDecDigits !== ''
) {
retVal += `.${postDecDigits}`;
}

Expand Down

0 comments on commit 2efc708

Please sign in to comment.