Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Last active March 27, 2020 15:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikoheikkila/83330a93f2fbdb2f8796b14bff114a61 to your computer and use it in GitHub Desktop.
Save nikoheikkila/83330a93f2fbdb2f8796b14bff114a61 to your computer and use it in GitHub Desktop.
TypeScript: Format floating euros to string notation
// Solution
type Formatter<T> = (a: T) => (b: T) => string
const numberFormatter: Formatter<number> = decimals => euros => euros.toFixed(decimals).replace(/\./, ',') + ' €'
const toCurrencyString = numberFormatter(2)
// Tests
const suites: [number, string][] = [
[-1, "-1,00 €"],
[0, "0,00 €"],
[1, "1,00 €"],
[10.01, "10,01 €"],
[59.00, "59,00 €"],
[Math.PI, "3,14 €"],
[NaN, "NaN €"]
]
for (const [euros, want] of suites) {
const got = toCurrencyString(euros)
if (got !== want) {
throw `Got ${got}, but wanted ${want}`
}
}
console.log('OK')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment