Last active
March 27, 2020 15:31
-
-
Save nikoheikkila/83330a93f2fbdb2f8796b14bff114a61 to your computer and use it in GitHub Desktop.
TypeScript: Format floating euros to string notation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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