Hyperlinkv0.8.0-beta.28

BigDecimal

BigDecimal.divideconsteffect/BigDecimal.ts:588
(that: BigDecimal): (self: BigDecimal) => Option.Option<BigDecimal>
(self: BigDecimal, that: BigDecimal): Option.Option<BigDecimal>

Divides BigDecimals safely.

When to use

Use to divide BigDecimal values while representing division by zero as Option.none.

Details

If the dividend is not a multiple of the divisor, the result will be a BigDecimal value with up to the default division precision. If the divisor is 0, the result will be Option.none().

Example (Dividing decimals safely)

import { BigDecimal, Option } from "effect"

console.log(
  Option.getOrThrow(
    BigDecimal.divide(
      BigDecimal.fromStringUnsafe("6"),
      BigDecimal.fromStringUnsafe("3")
    )
  )
) // BigDecimal(2)
console.log(
  Option.getOrThrow(
    BigDecimal.divide(
      BigDecimal.fromStringUnsafe("6"),
      BigDecimal.fromStringUnsafe("4")
    )
  )
) // BigDecimal(1.5)
console.log(
  Option.isNone(
    BigDecimal.divide(
      BigDecimal.fromStringUnsafe("6"),
      BigDecimal.fromStringUnsafe("0")
    )
  )
) // true
export const divide: {
  (that: BigDecimal): (self: BigDecimal) => Option.Option<BigDecimal>
  (self: BigDecimal, that: BigDecimal): Option.Option<BigDecimal>
} = dual(2, (self: BigDecimal, that: BigDecimal): Option.Option<BigDecimal> => {
  if (that.value === bigint0) {
    return Option.none()
  }

  if (self.value === bigint0) {
    return Option.some(zero)
  }

  const scale = self.scale - that.scale
  if (self.value === that.value) {
    return Option.some(make(bigint1, scale))
  }

  return Option.some(divideWithPrecision(self.value, that.value, scale, DEFAULT_PRECISION))
})