Skip to content

Instantly share code, notes, and snippets.

@emkis
Last active July 14, 2021 17:29
Show Gist options
  • Save emkis/469307892c671055e5dafe67cfa747b7 to your computer and use it in GitHub Desktop.
Save emkis/469307892c671055e5dafe67cfa747b7 to your computer and use it in GitHub Desktop.
Number.toFixed but without rounding the numbers
describe('toFixedWithoutRounding()', () => {
it('should return a string', () => {
const result = toFixedWithoutRounding(3271.24);
expect(typeof result).toBe('string');
});
it('should return expected numbers', () => {
expect(toFixedWithoutRounding(7933.2982426892, 1)).toBe('7933.2');
expect(toFixedWithoutRounding(7933.2982426892, 2)).toBe('7933.29');
expect(toFixedWithoutRounding(7933.2982426892, 3)).toBe('7933.298');
expect(toFixedWithoutRounding(103415.324)).toBe('103415.32');
expect(toFixedWithoutRounding(103415.324, 3)).toBe('103415.324');
expect(toFixedWithoutRounding(103415.324, 4)).toBe('103415.3240');
expect(toFixedWithoutRounding(0.893, 3)).toBe('0.893');
expect(toFixedWithoutRounding(0.893, 4)).toBe('0.8930');
expect(toFixedWithoutRounding(0.893, 5)).toBe('0.89300');
});
});
export function toFixedWithoutRounding(value: number, decimals = 2): string {
const [number, numberDecimals = ''] = (value ?? 0).toString().split('.');
const truncatedDecimals = numberDecimals.slice(0, decimals);
const formattedDecimals = truncatedDecimals.padEnd(decimals, '0');
const fixedNumber = [number, formattedDecimals].join('.');
return fixedNumber;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment