Skip to content

Instantly share code, notes, and snippets.

@tansongyang
Created September 17, 2019 21:18
Show Gist options
  • Save tansongyang/ccb15a545a5a775409dff74519e18c85 to your computer and use it in GitHub Desktop.
Save tansongyang/ccb15a545a5a775409dff74519e18c85 to your computer and use it in GitHub Desktop.
An attempt at a super simple money type that only supports addition
function toCents(value: number) {
return Math.round(value * 100);
}
function fromCents(value: number) {
return +(value / 100).toFixed(2);
}
class Money {
private cents: number;
get value() {
return fromCents(this.cents);
}
constructor(value: number) {
this.cents = toCents(value);
}
add(value: number | Money) {
const addedCents = typeof value === 'number' ? toCents(value) : value.cents;
const cents = this.cents + addedCents;
return new Money(fromCents(cents));
}
}
console.log(0.1 + 0.2);
console.log(new Money(0.1).add(0.2));
// Can try it out here: http://www.typescriptlang.org/play/#code/GYVwdgxgLglg9mABFOBhApmKBnAFANwEMAbEdALkTBAFsAjdAJwEpEBvAKEW8UfShCMkAWUJQAFgDpGccABMCJMogBUiAIwAGTcwDcHAL4cOoSLASJgMmhix4ipClVoMW7Ljz4ChiANSLHRAB6DW1mSRQAMRgAD3QFACY9Q2MIYkJsbERhBHQAT3ceRAAHRhgiKHRECEwcSmp6Jn0PbgBzfkQHMlxWTiKir0EkKzgbWrwJGGxJGrtkoqMW6oRsKEYQaDhGALJ6lyZepaLJ6dmcRABeZDRxnfR5nkWiwjkFLqcG10QAH2zcvMO-R4EBWUEQLzk8Vs5yuUDyxXQcGAnSUVQu6MQAHJPkxMYgAPzXaH2VGsSjvGbjfRA7ggsCrarjS7IcRTSl2Pzg15QqlHTz8IZUdAAdz+YHyuBGYzsuDO2GYD24RkWdOwcGI6EkxDgrVwmkk6k5+qS+lV6s12t14tFOXFeT1BvCEIdSWSQA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment