Open2

TypeScriptで通貨、金額を扱う場合はどの型を利用するのが良いのか?

pontaponta

Float / Double

  • Not precise and will turn into a bunch of errors
console.log(.1+.2)
// -> 0.30000000000000004

Decimal / Numeric

  • This type does not exists in JS and has to parse into String (not type safety)
  • Requires to use additional libs (decimal.js, big.js)
  • Not cross-language compatible (hard to migrate to other DB or language)
  • calculation looks too complex
x.div(y).plus(z).times(9).minus('1.234567801234567e+8').plus(976.54321).div('2598.11772')
x.sqrt().div(y).pow(3).gt(y.mod(z))    // true

Use integers of the smallest unit of the currency

  • $10.50 → 10500
  • cross-language compatible