Skip to content

Instantly share code, notes, and snippets.

@anthonybrown
Last active August 9, 2019 16:06
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 anthonybrown/6f5ab87ad11d7c2076feb027f1affa0f to your computer and use it in GitHub Desktop.
Save anthonybrown/6f5ab87ad11d7c2076feb027f1affa0f to your computer and use it in GitHub Desktop.
class Decimal {
constructor(number) {
this.precision = 8
this.number = number
this.integer = Math.floor(number)
this.fractional = Math.round(number * Math.pow(10, this.precision))
}
[Symbol.toPrimitive](hint) {
// hint can be: string, number, default
if (hint === 'string') {
return `Decimal(${this.number})`
}
return this.number
}
}
const value = new Decimal(7.77)
console.log(`${value}`) // Decimal(7.77)
console.log(`${value * 2}`) // 15.54
console.log(typeof `${value}`) // string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment