## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
# Non-trapped signals warn by default (see "Reporting signals" below). Silence
# them here so the flag examples stay focused; the warning is shown on its own.
options(decimal.report_flags = FALSE)

## ----setup--------------------------------------------------------------------
library(decimal)

## -----------------------------------------------------------------------------
get_decimal_context()

## -----------------------------------------------------------------------------
ctx <- decimal_context(precision = 2L, traps = character())

with_decimal_context(ctx, decimal("1.25") + decimal("0"))
get_decimal_context()

## -----------------------------------------------------------------------------
f <- function() {
  local_decimal_context(decimal_context(precision = 2L, traps = character()))
  decimal("1.234") + decimal("0")
}
f()
get_decimal_context()

## -----------------------------------------------------------------------------
ctx <- decimal_context(precision = 2L, traps = character())
with_decimal_context(ctx, {
  clear_decimal_flags()
  decimal("1.25") + decimal("0")
  decimal("1") / decimal("8")
  decimal_flags()
})

## -----------------------------------------------------------------------------
withr::with_options(
  list(decimal.report_flags = TRUE),
  with_decimal_context(
    decimal_context(precision = 2L, traps = character()),
    decimal("1.25") + decimal("0")
  )
)

## -----------------------------------------------------------------------------
withr::with_options(
  list(decimal.report_flags = TRUE),
  with_decimal_context(decimal_context(precision = 10L, traps = character()), {
    sqrt(decimal("2"))          # inexact, but silent -- expected of sqrt()
    decimal("1") / decimal("3") # inexact, and warns -- not every division is
  })
)

## ----error = TRUE-------------------------------------------------------------
try({
with_decimal_context(decimal_context(traps = "division_by_zero"), {
  decimal("1") / decimal("0")
})
})

## ----error = TRUE-------------------------------------------------------------
try({
strict <- decimal_context(
  traps = c("division_by_zero", "invalid_operation", "overflow", "inexact")
)
with_decimal_context(strict, decimal("1") / decimal("3"))
})

## -----------------------------------------------------------------------------
ctx <- decimal_context(precision = 3L, emin = -2L)
with_decimal_context(ctx, {
  x <- decimal(c("1E-2", "1E-3", "-0", "NaN", "sNaN"))
  number_class(x)
})

## -----------------------------------------------------------------------------
x <- decimal(c("NaN", "sNaN", "Infinity", "-0", "1E-3"))
is_qnan(x)
is_snan(x)
is.infinite(x)
is_zero(x)
is_signed(x)

