Skip to content

Instantly share code, notes, and snippets.

@laurenzcodes
Last active April 26, 2022 08:15
Show Gist options
  • Save laurenzcodes/70551e902506f1641bbfa0836e00302b to your computer and use it in GitHub Desktop.
Save laurenzcodes/70551e902506f1641bbfa0836e00302b to your computer and use it in GitHub Desktop.
Function to convert cents into euros using regex replace
const formatCents = (sum?: number | null): string =>
sum
? (sum / 100).toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".").replace(/\.([^.]*)$/g, ",$1")
: '0,00';
// Tests:
// it('formats cents into EURO (€) values', () => {
// expect(formatCents(1)).toEqual('0,01');
// expect(formatCents(10)).toEqual('0,10');
// expect(formatCents(100)).toEqual('1,00');
// expect(formatCents(1000)).toEqual('10,00');
// expect(formatCents(10000)).toEqual('100,00');
// expect(formatCents(100000)).toEqual('1.000,00');
// expect(formatCents(1000000)).toEqual('10.000,00');
// expect(formatCents(0)).toEqual('0,00');
// expect(formatCents(null)).toEqual('0,00');
// expect(formatCents(undefined)).toEqual('0,00');
// expect(formatCents(0.1)).toEqual('0,00');
// expect(formatCents(-100)).toEqual('-1,00');
// })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment